| | |
Is C++ unsafe? What'wrong of this codeblock?
Please support our C++ advertiser: Intel Parallel Studio Home
Thread Solved |
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)
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!
C++ Syntax (Toggle Plain Text)
#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!
>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:
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:
C++ Syntax (Toggle Plain Text)
#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; }
I'm here to prove you wrong.
•
•
•
•
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.
At first that code is like this:
C++ Syntax (Toggle Plain Text)
#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.
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.
C++ Syntax (Toggle Plain Text)
bot():password(567){}
I am totally baffled!!
Michelangelo
"The best place to find a helping hand is at the end of your own arm"
"The best place to find a helping hand is at the end of your own arm"
>Do you have any good idears to prevent it?
Yes, if you have code that looks like
But for reading strings, the getline method is often a much better choice:
>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:
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: C++ Syntax (Toggle Plain Text)
#include <iostream> #include <iomanip> int main() { char buffer[5]; std::cin>> std::setw ( 5 ) >> buffer; std::cout<< buffer; }
C++ Syntax (Toggle Plain Text)
#include <iostream> int main() { char buffer[5]; std::cin.getline ( buffer, sizeof buffer ); std::cout<< buffer; }
It's an initialization list for the class constructor. You can get the same effect (in this case) with this code:
C++ Syntax (Toggle Plain Text)
bot() { password = 567; }
I'm here to prove you wrong.
•
•
•
•
Can anyone tell me what this particular line does...C++ Syntax (Toggle Plain Text)
bot():password(567){}
I am totally baffled!!
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
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..
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..
Michelangelo
"The best place to find a helping hand is at the end of your own arm"
"The best place to find a helping hand is at the end of your own arm"
![]() |
Similar Threads
Other Threads in the C++ Forum
- Previous Thread: How do I put my output in colums of 4?
- Next Thread: Simple solution to database
| Thread Tools | Search this Thread |
api application array arrays based beginner binary bmp c++ c/c++ calculator char char* class classes code compile compiler console conversion count data delete deploy dll download dynamic dynamiccharacterarray email encryption error file format forms fstream function functions game givemetehcodez google graph gui homeworkhelp iamthwee ifstream input int java lib library linkedlist linker list loop looping loops map math matrix memory microsoft newbie news number numbertoword output pointer problem program programming project python random read recursion recursive reference rpg simple sorting string strings temperature template test text text-file tree unix url variable vector video visual visualstudio win32 windows winsock wordfrequency wxwidgets






