1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

pointer problem

Discussion in 'C' started by kaml.mish, Dec 10, 2010.

  1. kaml.mish

    kaml.mish New Member

    Joined:
    Dec 8, 2010
    Messages:
    2
    Likes Received:
    0
    Trophy Points:
    0
    Occupation:
    software engg
    Location:
    bangalore,india
    I have a program

    Code:
    char* ptr = new char[10];
    	*ptr =9;
    	std:cout<<ptr;
    	ptr = 8;
    	std::cout<<ptr;
    	return 0;
    
    may i know what exactly happens within the memory, when the program executes
     
  2. jimblumberg

    jimblumberg New Member

    Joined:
    May 30, 2010
    Messages:
    120
    Likes Received:
    29
    Trophy Points:
    0
    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?

    Jim
     
  3. xpi0t0s

    xpi0t0s Mentor

    Joined:
    Aug 6, 2004
    Messages:
    3,012
    Likes Received:
    203
    Trophy Points:
    0
    Occupation:
    Senior Support Engineer
    Location:
    England
    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++").
     

Share This Page