Reputation: 15868
First time I see this syntax: cin >> (ptr = new char);
Is this a sure way to allocate memory dynamically? What are the possible pitfalls?
int main()
{
char* charPtr;
std::cout << "Enter a string: ";
std::cin.getline((charPtr = new char), 5);//What's happening here?
std::cout << charPtr << "\n";
std::cout << "length: " << strlen(charPtr) << "\n";
std::cin.clear();///Clearing eventually errors flags
//Ignoring remained chars of the buffer.
std::cin.ignore(std::numeric_limits<int>::max(), '\n');
delete [] charPtr;//freeing memory
std::cout << "Enter a word: ";
std::cin >> (charPtr = new char);//ALLOCATING MEMORY FOR 1 CHAR
std::cout << charPtr << "\n";
std::cout << "length: " << strlen(charPtr) << "\n";
delete [] charPtr;//CRASH
return 0;
}
Upvotes: 1
Views: 154
Reputation: 103741
std::cin.getline((charPtr = new char), 5);
This allocates room for only one character, which must be taken up by the null terminator. As such, if the user enters any characters at all on this line, it results in a buffer overflow, undefined behavior.
delete [] charPtr;
Undefined behavior, since you allocated with new
, not new[]
.
std::cin >> (charPtr = new char);
Guaranteed buffer overflow, unless the user terminates standard input (e.g. with ctrl-z on Windows), since this will have to read at least one character, and store at least 2 (the read character(s), plus the null terminator).
delete [] charPtr;
I think you can guess what this is by now.
Upvotes: 4