Search code examples
cmemory-managementstring-literals

How do I free up the memory consumed by a string literal?


How do I free up all the memory used by a char* after it's no longer useful?

I have some struct

struct information
{
/* code */
char * fileName;
}

I'm obviously going to save a file name in that char*, but after using it some time afterwards, I want to free up the memory it used to take, how do I do this?

E: I didn't mean to free the pointer, but the space pointed by fileName, which will most likely be a string literal.


Solution

  • There are multiple string "types" fileName may point to:

    1. Space returned by malloc, calloc, or realloc. In this case, use free.

    2. A string literal. If you assign info.fileName = "some string", there is no way. The string literal is written in the executable itsself and is usually stored together with the program's code. There is a reason a string literal should be accessed by const char* only and C++ only allows const char*s to point to them.

    3. A string on the stack like char str[] = "some string";. Use curly braces to confine its scope and lifetime like that:

      struct information info;
      {
          char str[] = "some string";
          info.fileName = str;
      }
      printf("%s\n", info.fileName);
      

      The printf call results in undefined behavior since str has already gone out of scope, so the string has already been deallocated.