does delete clear the memory?
CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 14 of 14

Thread: does delete clear the memory?

  1. #1
    Join Date
    May 2010
    Posts
    83

    Smile does delete clear the memory?

    Hi,

    i store critical information in a

    char* secret;
    secret = new char[123];

    after using it, i delete it:

    delete secret;


    Now:
    Is there any way of re-allocating the "deleted" memory & restoring the data?
    Would it make sense to ZeroMemory() the secret buffer before deleting it?

  2. #2
    Join Date
    Jan 2009
    Posts
    1,689

    Re: does delete clear the memory?

    No, deleting it releases it and your program is free to use it for anything else. realloc does something different.

  3. #3
    Join Date
    Jun 2010
    Location
    Germany
    Posts
    2,583

    Re: does delete clear the memory?

    Quote Originally Posted by felix1432 View Post
    Is there any way of re-allocating the "deleted" memory & restoring the data?
    Another process can read your deleted memory as long as it hasn't been overwritten yet. It doesn't even need to re-allocate anything to do so.

    The delete operator doesn't overwrite anything, but your destructor can do, and it is called by delete. Of course, the secret memory area needs to be owned by some sort of object in order to do so, instead of a naked char array.

    Would it make sense to ZeroMemory() the secret buffer before deleting it?
    Yes (see above). But it would be safer to use SecureZeroMemory() instead, because a call to ZeroMemory() can happen to get optimized away by the compiler.

    HTH
    I was thrown out of college for cheating on the metaphysics exam; I looked into the soul of the boy sitting next to me.

    This is a snakeskin jacket! And for me it's a symbol of my individuality, and my belief... in personal freedom.

  4. #4
    Join Date
    Jan 2009
    Posts
    1,689

    Re: does delete clear the memory?

    What exactly are you trying to do anyway that you require this?

  5. #5
    Join Date
    Apr 2008
    Posts
    118

    Re: does delete clear the memory?

    Quote Originally Posted by felix1432 View Post
    Is there any way of re-allocating the "deleted" memory & restoring the data?
    Would it make sense to ZeroMemory() the secret buffer before deleting it?

    This is very much dependent on your compiler and architecture. The long and the short of it is if you can point to that memory, and your system lets you read it, and it hasn't been written over, then yes; it can be read again.

    Here's an example.

    Code:
    char* p_firstChar     = new char;
    char* p_secondChar = new char;
    
    // These two chars could have been allocated in consecutive memory locations
    
    p_secondChar = X; // Your secret letter
    delete p_secondChar;
    
    p_firstChar++; // p_firstChar now points one character beyond where it originally pointed.
                            //  This could be pointing at the memory allocated for p_secondChar.
    
    char secretLetter = *p_firstChar; // Read the contents of where p_secondChar used to point.
                                                         // Compiler/system dependent, you could be reading "X"
    The standard dictates the following:

    Delete calls the objects destructor (note that destructors are a bit special for primitives like char).
    Delete call a deallocation function.

    That deallocation function in turn "shall deallocate the storage referenced by the pointer". The standard specifies that the memory is then "reclaimed".

    This seems to indicate that if your destructor doesn't trash the memory, nothing else can be relied on to either. If you want to ensure it does, I suggest you add a destructor to your object that writes over the top of it.

  6. #6
    Join Date
    Jun 2009
    Location
    France
    Posts
    2,281

    Re: does delete clear the memory?

    Quote Originally Posted by felix1432 View Post
    Hi,

    i store critical information in a

    char* secret;
    secret = new char[123];

    after using it, i delete it:

    delete secret;
    From a C++ point of view, deallocation simply means to return ownership of memory from the program back to the OS. The memory, and memory contents, still exist. In theory, your program is not allowed to reference that memory any more. You can try, but the resulting behaviour is undefined.

    There are ways to trash the memory (using Moschops' words). In particular, in most debug builds, the compiler purposefully writes bogus patterns in allocated but un-initialized data, or writes data before deallocating. This helps during the debug process.

    For example, if you read a valuen and it turns out it's hex value is "0xdeadbeef", it has high chances of meaning you never initialized that memory. If you read "0xdeadmeat", it can mean the memory was already released. None of this is a guarantee, but is usually a good indicator. I don't use this, so my patterns might be wrong, but you get the point.

    In release builds, this never happens, because it is too costly at run-time.

    Now, back to your issue, trashing the memory so no-one can retrieve it: For starters, know that it is impossible to keep someone from looking into your process' memory. At best, you can try to encrypt it, but it is not fail proof, especially since there are high chances the un-encrypted data is also in memory.

    Still, the easiest way to do what you are asking for is either to implement it in the destructor. This would be extremly dangerous if any of your members are not PODs though. or...

    Quote Originally Posted by Moschops View Post
    This seems to indicate that if your destructor doesn't trash the memory, nothing else can be relied on to either. If you want to ensure it does, I suggest you add a destructor to your object that writes over the top of it.
    You can overload operator new/delete for your type. This way, you keep a normal destructor, and the operator delete will be responsible for trashing the memory after the object has been safely destroyed. The downside is that it doesn't work for auto (stack allocated) objects, but those are usually overwritten in less than a jiffy.
    Is your question related to IO?
    Read this C++ FAQ LITE article at parashift by Marshall Cline. In particular points 1-6.
    It will explain how to correctly deal with IO, how to validate input, and why you shouldn't count on "while(!in.eof())". And it always makes for excellent reading.

  7. #7
    Join Date
    Jun 2010
    Location
    Germany
    Posts
    2,583

    Re: does delete clear the memory?

    Quote Originally Posted by monarch_dodra View Post
    0xdeadmeat


    [...] This would be extremly dangerous if any of your members are not PODs though.
    Does that mean that member (and base class?) destructors are called after those of owner (/derived) classes? In that case: Oops! I failed to take that into account while writing post #3.
    I was thrown out of college for cheating on the metaphysics exam; I looked into the soul of the boy sitting next to me.

    This is a snakeskin jacket! And for me it's a symbol of my individuality, and my belief... in personal freedom.

  8. #8
    Join Date
    Jun 2009
    Location
    France
    Posts
    2,281

    Re: does delete clear the memory?

    Quote Originally Posted by Eri523 View Post


    Oops, probably baadbeef or something

    Does that mean that member (and base class?) destructors are called after those of owner (/derived) classes? In that case: Oops! I failed to take that into account while writing post #3.
    Yes.

    Objects and destroyed in the opposite order they were constructed:
    Base is constructed before Destroyed
    Members are constructed before you enter the class constructor body.

    More importantly:

    Code:
    my_class::~my_class()
    {
        trash_memory();
    } // <- Members are actually destroyed here! But the memory is already trashed!!!
    Is your question related to IO?
    Read this C++ FAQ LITE article at parashift by Marshall Cline. In particular points 1-6.
    It will explain how to correctly deal with IO, how to validate input, and why you shouldn't count on "while(!in.eof())". And it always makes for excellent reading.

  9. #9
    Join Date
    Feb 2008
    Posts
    22

    Re: does delete clear the memory?

    Quote Originally Posted by felix1432 View Post
    Hi,

    i store critical information in a

    char* secret;
    secret = new char[123];

    after using it, i delete it:

    delete secret;
    You are not freeing the memory correctly. Use
    Code:
    delete [] secret;

  10. #10
    Join Date
    May 2010
    Posts
    83

    Thumbs up Re: does delete clear the memory?

    thanks a lot for the replies, guys.

    You are not freeing the memory correctly. Use
    delete buffer; compiles fine, where`s the difference, or rather, why doesnt VS complain?
    what do the "[]" stand for?


  11. #11
    Join Date
    Jun 2010
    Location
    Germany
    Posts
    2,583

    Re: does delete clear the memory?

    Quote Originally Posted by monarch_dodra View Post
    Oops, probably baadbeef or something
    Referring to 0xdeadbeef makes me think you are talking about MS stuff. For uninitialized memory they use 0xcccccccc on the stack and 0xcdcdcdcd on the heap. 0xbaadf00d is also MS.

    Someone once posted a link to this article here some time ago which I found quite interesting. (I think it was in the file formats thread, but I don't remember who deserves the merits for the link.)

    Quote Originally Posted by felix1432 View Post
    delete buffer; compiles fine, where`s the difference, or rather, why doesnt VS complain?
    what do the "[]" stand for?
    The delete with [] is for object arrays (allocated with new someType[someCount]), the one without is for single objects (allocated with new someType). The compiler won't complain about mixing them up because it can't tell from the pointer type whether the pointer refers to a single object or an array.

    As I understand it, it doesn't really make a difference which one you use as long as the object or objects in an array the pointer points to don't have a destructor. (But of course you should get accustomed to good practice and always use the right one anyway.) But if it has one, you are summoning the potentially catastrophic consequences of undefined behaviour if you don't use the correct one.
    Last edited by Eri523; December 17th, 2010 at 02:04 PM.
    I was thrown out of college for cheating on the metaphysics exam; I looked into the soul of the boy sitting next to me.

    This is a snakeskin jacket! And for me it's a symbol of my individuality, and my belief... in personal freedom.

  12. #12
    Join Date
    Jun 2009
    Location
    France
    Posts
    2,281

    Re: does delete clear the memory?

    Quote Originally Posted by felix1432 View Post
    thanks a lot for the replies, guys.



    delete buffer; compiles fine, where`s the difference, or rather, why doesnt VS complain?
    what do the "[]" stand for?

    Don't EVER assume a c++ program is correct because it compiles, or it runs.

    Anyways, [] stands for array, and you have to use delete[] to delete an array. It compiles fine because it will create a runtime problem. Why? That is just the way it is. Holdover from C.
    Is your question related to IO?
    Read this C++ FAQ LITE article at parashift by Marshall Cline. In particular points 1-6.
    It will explain how to correctly deal with IO, how to validate input, and why you shouldn't count on "while(!in.eof())". And it always makes for excellent reading.

  13. #13
    Join Date
    Aug 2005
    Location
    San Diego, CA
    Posts
    1,054

    Lightbulb Re: does delete clear the memory?

    zeromemory is a windows API isn't it? Anyway the use of delete can be avoided if you use std::vector or std::deque. The OP probably can't say but if this is a person working in defense they may have a requirement to clear memory when software components are destroyed. Clearing memory doesn't necessarily mean zero initialization either but it could. In an object oriented system you really need to use your destructors to reset memory and to trap exceptions. You might need to simply set each class attribute back to some default value. A more std solution would be to use memset or std::fill to clear values in arrays before deallocating the memory.

  14. #14
    Join Date
    Jan 2009
    Posts
    1,689

    Re: does delete clear the memory?

    ZeroMemory is just a macro, you should try to use standard C++ wherever possible:

    Code:
    memset(secret, 0, size of secret)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  


Azure Activities Information Page

Windows Mobile Development Center


Click Here to Expand Forum to Full Width

This is a CodeGuru survey question.


Featured


HTML5 Development Center