Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is memory associated with a char *foo() function freed (in C)?

If I have a function return a pointer to a string, something like below (maybe different sytnax), is that string freed from memory at the end of the calling function foo?

void foo(){
    char *string = function();
    // Is string freed at the end of this function?
}

char *function(){
    return "string";
}

I’m asking this because I understand that if I were to malloc() the memory, it would not be freed at the end of foo (unless I go and free it myself).

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

No. "string" is stored in a read-only portion of the program’s memory and is never freed.

The memory of a C program can be roughly categorized as…

  • The code.
  • Constants like "string" and 42.
  • Globals and static variables.
  • Stack (char foo[50] or int i inside a function)
  • Heap (malloc, calloc, realloc)

Constants, globals, and statics are never deallocated.

The stack is deallocated when the function returns. This is why one should not return pointers to memory allocated on the stack. Simple values like int and float are fine because the value is copied.

// Don't do this, foo will be deallocated on return.
char *function(){
    char foo[10];
    strcpy(foo, "string");
    return foo;
}

// Don't do this either.
char *function(){
    char foo = 'f';
    return &foo;
}

// Nor this.
int *function(){
    int i = 42;
    return &i;
}

// But this is fine.
char function(){
    char foo = 'f';
    return foo;
}

Heap is only deallocated when it is freed.

See Where will the Initialized data segment values are stored before run time? and Memory Layout of a C Program for the gory details.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading