Go4Expert (http://www.go4expert.com/)
-   C (http://www.go4expert.com/forums/c/)
-   -   pointer problem (http://www.go4expert.com/forums/pointer-problem-t24144/)

kaml.mish 10Dec2010 20:18

pointer problem
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 10Dec2010 21:48

Re: pointer problem
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 12Dec2010 20:57

Re: pointer problem
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++").

All times are GMT +5.5. The time now is 21:06.