arrayscscopestring-literalsstorage-duration

When is a char array heap vs stack allocated?


I have a hard time understanding when and when not a char array is heap/stack allocated, depending on the way they are declared. For example:

void test()
{
   char *str1 = "MyString1";  // do i need to free this ??
   char str2[] = "MyString2"; //this is clearly on the stack

}

Should i call free(str1) before exiting test()??


Solution

  • You only have to free what you allocated. In your example, there is nothing to free, because the compiler created a static storage for it, which can not and must not be freed.

    Wether you have to free something also depends on the functions you are calling. For example, if you call strdup() then you need to free the returned pointer:

    char *p = strdup("MyString");
    free(p);
    

    However, if you for example, call strcpy() then you don't call free.

    char buffer[100];
    strcpy(buffer, "MyString");
    // Don't free, as you created a local buffer on the stack and strcpy() doesn't allocate anything.
    

    Here you would have to free because you allocated it:

    char *p = malloc(100);
    strcpy(p, "MyString");
    free(p);