Releasing System-Allocated Memory

In the statements
   char * str = "abc";
   str = "xyz";
is malloc or one of its relatives used for the memory allocation
I assume that there is no memory leak when these statements are executed.
Does the system use free(...) before reallocating the memory
If one needs to release the allocated memory some time before the execution of the second statement, can one use free((char *) (str-1));
Thanks.



Answer this question

Releasing System-Allocated Memory

  • Robert Schroeder

    Thanks, Jonathan.
    Calling free in these circumstances does not seem to cause a crash or raise an exception, but I am using MS VC++ Version 6. Perhaps later versions of C++ are less tolerant. 

  • divs

    Andrew: there is no dynamic memory allocation involved in these statements. At link time storage is allocated for the strings "abc" and "xyz" within the read-only portion of the program image and it is the address of this storage that is assigned to the variable str.

    Calling free on str would cause the program to either crash or raise an exception as the address passed to free would not be a valid dynamic memory address.

  • Releasing System-Allocated Memory