new without delete => bad ?

This is a discussion on new without delete => bad ? within the C++ Programming forums, part of the General Programming Boards category; I'm not sure if I'm missing something, or just reading into the paranoia about C++ and garbage collection too much. ...

  1. #1
    Registered User
    Join Date
    Oct 2005
    Posts
    88

    new without delete => bad ?

    I'm not sure if I'm missing something, or just reading into the paranoia about C++ and garbage collection too much.

    Say I have the code below:

    Code:
    void f( int env_cl )
    {
    
    char *buf = new char[env_cl]; for( int i=0; i<= env_cl && buf[i] != EOF; i++ ) { buf[i] = std::cin.get(); } buf[i] = 0x00; this->unencode( buf );
    }
    Since the function isn't returned to after calling 'unencode()', from what I gather the variable 'buf' will just stay there for as long as the OS allows it to. I assumed that would leak memory over time, but I can't seem to create that leak.

    I am missing something, right? You have to 'delete' each variable created on the free store don't you?

    PS. I know using strings would solve this problem, but it would create others, not to mention the fact that I would still not know the answer.

  2. #2
    Registered User
    Join Date
    Jan 2005
    Posts
    7,317
    Yes, that is a memory leak (assuming unencode doesn't call delete []). You probably won't notice the leak in this case since it is only leaking one byte for each character it gets from the standard input. But if you gave it large enough input you would eventually notice the memory usage growing and growing.

    BTW, it should be i < env_cl in your for loop control (not <=). In fact, it should be i < (env_cl-1) so that room is left for the null character.

  3. #3
    Registered User
    Join Date
    Sep 2005
    Posts
    36
    But the memory is still deallocated upon program termination right?

  4. #4
    ---
    Join Date
    May 2004
    Posts
    1,379
    The OS usually does that but it doesn't have to.

  5. #5
    Registered User
    Join Date
    Oct 2005
    Posts
    88
    I've changed the code a little, but another strange thing cropped up:
    Code:
    void f( int env_cl )
    {
    	char *buf = new char[env_cl+1];
    	for( int j=0; j< env_cl && buf[i] != EOF; j++ ) {
    		buf[j] = std::cin.get();//>> buf;
    	}
    	buf[env_cl] = 0x00;
    
            strcpy( env_qs, buf );
    	delete [] buf;                   
    	this->unencode( env_qs );
    }
    By the time the code reaches delete [], buf is apparently gone... In none of the documentation I've read does it say that strcpy deletes the char * it's copying from.

    Wierd. I just hope buf has actually been deleted.

  6. #6
    Registered User
    Join Date
    Jan 2005
    Posts
    7,317
    Sure it has. You use new[] to allocate space for it and then call delete[] to free the memory. I don't what you are doing to determine whether buf is gone or not, but you can't really tell by looking at it.

  7. #7
    Unregistered User
    Join Date
    Sep 2005
    Location
    Antarctica
    Posts
    341
    windows 95 and higher will delete the memory upon program termination

  8. #8
    Registered User hk_mp5kpdw's Avatar
    Join Date
    Jan 2002
    Location
    Northern Virginia/Washington DC Metropolitan Area
    Posts
    3,788
    Quote Originally Posted by drrngrvy
    Since the function isn't returned to after calling 'unencode()', from what I gather the variable 'buf' will just stay there for as long as the OS allows it to.
    The variable buf itself is allocated on the stack and will get popped off once the function ends just like any other local variable. It is the memory, allocated via new, and not the variable that persists after the function call has completed. Without passing the address of this memory back or somehow keeping track of it otherwise, you lose your handle to it and lose the ability to delete it later on therefore causing a memory leak within the program.
    "Owners of dogs will have noticed that, if you provide them with food and water and shelter and affection, they will think you are god. Whereas owners of cats are compelled to realize that, if you provide them with food and water and shelter and affection, they draw the conclusion that they are gods."
    -Christopher Hitchens

  9. #9
    I am me, who else?
    Join Date
    Oct 2002
    Posts
    250
    Quote Originally Posted by rockytriton
    windows 95 and higher will delete the memory upon program termination
    Just to quote this, it is true, however don't let this lull you into thinking it'll be ok. Ocassionally and I admit I "worked hard" at this... you can cause really funky errors where windows can't cope (and occassionally blue screens), however those are extremely rare from what I've seen. However the warning remains, don't let windows protect you from your own mistakes

  10. #10
    Registered User
    Join Date
    Oct 2005
    Posts
    88
    Thanks for the input guys. One problem though:

    Quote Originally Posted by Daved
    Sure it has. You use new[] to allocate space for it and then call delete[] to free the memory. I don't what you are doing to determine whether buf is gone or not, but you can't really tell by looking at it.
    I meant that the line delete [] buf causes a null reference exception (or whatever it's called). As in, after using strcpy() to copy buf to env_qs, it's illegal to call delete [] on buf. I really don't know why that happens... Any ideas.

  11. #11
    Registered User
    Join Date
    Jan 2005
    Posts
    7,317
    >> As in, after using strcpy() to copy buf to env_qs, it's illegal to call delete [] on buf.

    That shouldn't happen. The strcpy function shouldn't change buf, and you should still be able to delete[] it successfully. If you are getting a crash there, it is due to some other problem in your program.

  12. #12
    Registered User
    Join Date
    Oct 2005
    Posts
    88
    OK thanks. I solved the memory leak, but the code isn't as obvious as I thought it could have been. I can see why people refer to memory management as 'niggly'.

    I ran into a few (as yet unresolved) issues along the way, but I'll keep them to myself since they're not on topic. One that is though: aren't there any delete-like operators that will work on both free-store and non free-store variables? It would make things cleaner if there was one.

  13. #13
    Registered User
    Join Date
    Jan 2005
    Posts
    7,317
    You don't need to delete non free-store variables, and it would make the language way too slow to have built-in capability to figure out when you are using delete on a non-free store memory.

    The easiest way to not worry about these things is to take advantage of good C++ design and available tools to leave the memory management to existing classes. That is why the C++ string class is recommended over C style strings, because it manages the memory for you - no leaks, fewer worries. The same is true for vector versus C style arrays.

    Most often the "other" problems created by C++ solutions are just a little extra work to learn the appropriate syntax. But doing so will save you from many of these types headaches in the future.

  14. #14
    semi-colon generator ChaosEngine's Avatar
    Join Date
    Sep 2005
    Location
    Chch, NZ
    Posts
    597
    Quote Originally Posted by drrngrvy
    aren't there any delete-like operators that will work on both free-store and non free-store variables? It would make things cleaner if there was one.
    why would you need to delete non-heap variables?

    Manual memory management is, in general, a receipe for disaster. Good coding practice in C++ is to use the RAII idiom. Specifically have a look at the standard library auto_ptr and (even more useful) the boost shared_ptr classes.

    Hope that helps
    Last edited by ChaosEngine; 10-13-2005 at 07:24 PM. Reason: yeah... what daved said!
    "I saw a sign that said 'Drink Canada Dry', so I started"
    -- Brendan Behan

    Free Compiler: Visual C++ 2005 Express
    If you program in C++, you need Boost. You should also know how to use the Standard Library (STL). Want to make games? After reading this, I don't like WxWidgets anymore. Want to add some scripting to your App?

  15. #15
    Registered User
    Join Date
    Aug 2005
    Posts
    1,267
    I realize you are concentrating on memory allocation, but haven't you noticed the error in this loop???
    Code:
    	for( int j=0; j< env_cl && buf != EOF; j++ ) {
    		buf[j] = std::cin.get();//>> buf;
    	}
    Hint: when is buf ever going to be EOF? Answer: It won't!

Page 1 of 2 12 LastLast
Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Smart pointer class
    By Elysia in forum C++ Programming
    Replies: 63
    Last Post: 11-03-2007, 07:05 AM
  2. MSVC 2003 Debugging delete
    By Bajanine in forum Windows Programming
    Replies: 2
    Last Post: 09-09-2007, 12:15 PM
  3. Proper Usage of the delete Operator
    By thetinman in forum C++ Programming
    Replies: 7
    Last Post: 04-25-2007, 11:53 PM
  4. delete by copy only for non-children nodes?
    By patricio2626 in forum C++ Programming
    Replies: 17
    Last Post: 11-18-2006, 07:37 AM
  5. Shocking(kind of)
    By Shadow in forum A Brief History of Cprogramming.com
    Replies: 25
    Last Post: 12-10-2002, 07:52 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21