Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C free variables declared inside function

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()?

like image 871
pasadinhas Avatar asked May 05 '26 05:05

pasadinhas


2 Answers

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

like image 195
asio_guy Avatar answered May 06 '26 19:05

asio_guy


The caller will need to make sure str is freed. temp was not dynamically allocated, so you cannot free it.

like image 38
Elazar Avatar answered May 06 '26 18:05

Elazar