Hi,sir.I encounterred a person who said that C++ is an unsafe language.I try the follow code ,but when I input an non-int type,the program will fall in a bad loop.(gcc4.1 in Linux)

#include <iostream>
#include <string>
 
using namespace std;
class bot
{
private:
    int password;
public:
    bot():password(567){}
    virtual ~bot(){};
    bool checkpwd(const int pwd)
      {return (password == pwd);}
};
 
int s;
bot b;
 
int main()
{
    for(;;)
     {
       cout<<"Enter password:";
       cin>>s;
 
       if(b.checkpwd(s))
         {
            cout<<"Access permitted"<<endl<<endl;
            break;
          }
         else
             cout<<"Access denied"<<endl<<endl;
        }
return 0;
}

I wanner whether the type int is unsafe or the C++'s object in unsafe? If I use string type to define the password,there won't be this error.And I know that this code is not a good C++ program,for testing this problem,so I do it.
Help me,please^_^
Thank you very much!

Recommended Answers

All 11 Replies

>I encounterred a person who said that C++ is an unsafe language.
It is and it isn't. C++ doesn't do much to protect you from doing something wrong, so in that light it's an unsafe language. However, if you do things right, it's perfectly safe. I'd say that person was wrong for making such an absolute and general statement, but a lot of absolute and general statements have some ring of truth.

>but when I input an non-int type,the program will fall in a bad loop.
That's because the code isn't written to handle unexpected input. In this case, cin expects a valid integer. If you don't give it a valid integer, it goes into an error state and won't let you read any more input until the errors are corrected and the error state is cleared. This isn't a case of C++ being unsafe, it's a case of the author not knowing how to properly handle I/O in C++. Try this:

#include <iostream>
#include <string>
#include <ios>    // for streamsize
#include <limits> // for numeric_limits

using namespace std;
class bot
{
private:
  int password;
public:
  bot():password(567){}
  virtual ~bot(){};
  bool checkpwd(const int pwd)
  {return (password == pwd);}
};

int s;
bot b;

int main()
{
  for(;;)
  {
    cout<<"Enter password: ";

    if ( cin>>s ) {

      if(b.checkpwd(s))
      {
        cout<<"Access permitted"<<endl<<endl;
        break;
      }
      else
        cout<<"Access denied"<<endl<<endl;
    }
    else if ( !cin.eof() ) {
      // Notify the user
      cerr<<"Invalid password\n";

      // Clear the error state
      cin.clear();

      // Remove the bad input
      cin.ignore ( numeric_limits<streamsize>::max(), '\n' );
    }
    else {
      // The user entered EOF; assume he wants to exit
      break;
    }
  }
  return 0;
}

Thank you very much!

Member Avatar for iamthwee

If your password actually needs to be an integer, which I doubt it needs to be, you be would better taking the input as a string and then converting it to an integer, after parsing out the crap.

If your password actually needs to be an integer, which I doubt it needs to be, you be would better taking the input as a string and then converting it to an integer, after parsing out the crap.

Ah,this thread is not about how to design the password,but how about the C++ 's safty. C and C++ can not prevent the memory from overflowing,so I want to know how to defend it by myself.

At first that code is like this:

#include <iostream>
#include <string.h>
using namespace std;
class bot
{
private:
char password[8];
public:
bot(){strcpy(password, "abc");};
virtual ~bot(){};
bool checkpwd(const char *pwd){return (!strcmp(password, pwd));};
};
char s[8];
bot b;
int main()
{
  for(;;)
  {
    cout << "Enter password: ";
    cin >> s;
    if (b.checkpwd(s))
    {
      cout << "Access permitted.\n\n";
      break;
    }
    else
      cout << "Access denied.\n\n";
  }
  return 0;
}

Ah,the author may not know well about C++;) .
In that code,the problem is not about the type safe,but a memory buffer overflowing.If you input over twenty charactors,the password will be modified by after the 12th charactors.

Do you have any good idears to prevent it?help me please!
Thank you!

> Do you have any good idears to prevent it?help me please!
Yes, you use fgets() in C, and getline() in C++
Both of which allow you to specify the maximum length of input.

> C and C++ can not prevent the memory from overflowing
Only if you use the poorer archaic API calls which are inhertited from history.

Once again, read EVERYTHING as a string using one of the API calls which specifies a length. Once you have the string in memory, with a known length, then you can make the right choices as to what to do with it.

bot():password(567){}

Can anyone tell me what this particular line does...
I am totally baffled!!

>Do you have any good idears to prevent it?
Yes, if you have code that looks like cin>> s where s is an array, it's wrong. As you've seen, that doesn't protect against a buffer overflow. You can fix it by setting a maximum field width if you really have to use the >> operator:

#include <iostream>
#include <iomanip>

int main()
{
  char buffer[5];

  std::cin>> std::setw ( 5 ) >> buffer;
  std::cout<< buffer;
}

But for reading strings, the getline method is often a much better choice:

#include <iostream>

int main()
{
  char buffer[5];

  std::cin.getline ( buffer, sizeof buffer );
  std::cout<< buffer;
}

>Can anyone tell me what this particular line does...
It's an initialization list for the class constructor. You can get the same effect (in this case) with this code:

bot()
{
  password = 567;
}
bot():password(567){}

Can anyone tell me what this particular line does...
I am totally baffled!!

This is a initialization member list which is always in the constructor to initialize the class' data member when it is declaring. There's some different from initializing it in the constructor. The latter you do will initialize the data member after all the data members have been delared.
Ah,I am sorry of that my English is so poor that I can't use it to make you understand:'( . You have to look at "C++ Primer" to study it.

Sorry:pretty:

Thanks meiyanto for trying your best to explain that to me but seriously, it all went over my head thanks to your outrageous vocab...

Bt thanks anyways..

>It's an initialization list for the class constructor.

I believe this one was new to me..

Where would i be if not for the Daniweb experts ??
Thanks again..

>I encounterred a person who said that C++ is an unsafe language.
It is and it isn't. C++ doesn't do much to protect you from doing something wrong, so in that light it's an unsafe language. However, if you do things right, it's perfectly safe. I'd say that person was wrong for making such an absolute and general statement, but a lot of absolute and general statements have some ring of truth.

The definition of 'safe' and 'unsafe' are usually clearly and precisely defined, or definable, and under all versions I know, C++ is unsafe. It's not type-safe, and it's not safe from memory leaks, and exception-wise, it is unsafe, too (and will always be, if you have exit). To state that doing things right makes it perfectly safe is to annihilate any definition of safety, except the one that has to do with whether the language is practical or not.

>The definition of 'safe' and 'unsafe' are usually clearly and precisely defined, or definable
Then please provide your reference to a reputable source that makes this definition.

>To state that doing things right makes it perfectly safe is to annihilate any definition of safety
Rather, it makes it a moot point. If you do things wrong, every language will be unsafe in some form or another. If a "safe" language throws an exception, you don't catch it, and the program crashes with an unhandled exception error, how is that safe? It's still a critical meltdown, and the reason it happened in a supposedly safe environment is because the programmer didn't do things right.

If you want to compare safety, you have to define the extent to which safety applies. If you want to break the rules or do something with obviously broken effects to prove that C++ is unsafe, I'll do the same thing with your favorite "safe" language to prove the logical inconsistency.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.