C free variables declared inside function

c++freefunctionmallocmemory-leaks

Imagine this code:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define MAXSTRSIZE 2048    

int main()
{
    char *str;

    str = get_string();

    return 0;
}

char * get_string()
{
    char temp[MAXSTRSIZE], *str;

    fgets(temp,MAXSTRSIZE,stdin);
    str = malloc( sizeof(char) * (strlen(temp) + 1) );
    strcpy(str, temp);

    return str;
}

Do I need to free() the temp variable in function get_string?
What if did the get_string code inside the main()?

Best Solution

free call applies only for dynamically allocated memory and not for static memory allocations

so if there is anything allocated dynamically using malloc/calloc needs to be freed when ever the reference count to the specified memory block will reach to zero, on the other hand statically allocated memory must not be freed at all, the program itself I suppose will not have right to free the memory allocated statically

in case you try to free static memory compiler ideally throws a warning at compile time like below warning: attempt to free a non-heap object

in case, where the warning is ignored will present a nice runtime crash at free

* glibc detected ./a.out: free(): invalid pointer:*

never attempt to free a non-heap object