Arrays/Pointers

This works, and I'm THINKING it's bad practice but I want to know why exactly.

1
2
3
4
5
6
7
8
9
10
11
12
int main()
{
	using namespace std;

	char * name = new char;

	cin >> name;

	cout << name;

	return 0;
}


I know that you're simply requesting enough memory from the heap to store 1 character and returning that address to "name", but when I input more than 1 character, it doesn't stop me. I assume I'm over-writing other data on the heap.

Additionally, I'm assuming that it outputs everything I just input because "cout" simply receives the address of a character and continues to read consecutive characters until it hits the NULL character (much how strings are output).

Above are my GUESSES at whats happening - my question is what exactly is happening, why does it work and why is it bad?
first of all, you have a memory leak (new without delete)

second, when you pass char* to operator>>, it assumes that it is dealing with a C-style string (null-terminated array of char), and that is what it is going to store. Even if you enter only one character, it will write two characters to memory: the one you entered, and a terminating null into the next location in memory to construct a valid C-string. And, as you guessed, this will write into unallocated memory, which is a form of undefined behavior

Undefined behavior is bad because anything at all can happen - crash if you are lucky, occasional problems in unrelated parts of the program that fix themselves in the debugger if you are less lucky.

Likewise, operator<< for char* assumes it is dealing with a C-string and keeps reading successive characters until encountering the null, which is of course again an error unless name[0] is zero.


Topic archived. No new replies allowed.