pointer problem

kaml.mish's Avatar, Join Date: Dec 2010
Newbie Member
I have a program

char* ptr = new char[10];
	*ptr =9;
	ptr = 8;
	return 0;
may i know what exactly happens within the memory, when the program executes
jimblumberg's Avatar
Ambitious contributor
Have you tried to put this into a program and then compile and run the program?

Did the program compile?

What did the program output?

xpi0t0s's Avatar, Join Date: Aug 2004
First line allocates an array of 10 chars on the heap and assigns the memory location to ptr.
Second line stores 9 in ptr[0].
Third line depends on your OS and characterset, it will display whatever character corresponds to 9, plus whatever else is in ptr, and it will keep printing until it hits a null. So this most likely displays junk on the screen.
Fourth line overwrites ptr with the value 8 and creates a memory leak, because the location of the char[10] you assigned is now lost. This isn't Java and the garbage collector (which doesn't exist) won't clean up after you.
Fifth line displays on the screen whatever is at memory location 8, which is probably junk, or you might get a core dump.

So in short, whoever wrote that code has no idea what they're doing. Or thinks they're still using Java (perhaps having believed the lie "Java is like C++").