Home > Back-end >  Is memory associated with a char *foo() function freed (in C)?
Is memory associated with a char *foo() function freed (in C)?

Time:07-20

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).

CodePudding user response:

No. Memory for "string" is allocated for the duration of program execution.

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.

  •  Tags:  
  • c
  • Related