3

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

Mat
  • 202,337
  • 40
  • 393
  • 406
pasadinhas
  • 353
  • 2
  • 6
  • 22

4 Answers4

4

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

asio_guy
  • 3,667
  • 2
  • 19
  • 35
3

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

Elazar
  • 20,415
  • 4
  • 46
  • 67
3

You must free() whatever you malloc(), it does not matter when or where but it must be happen to prevent a memory leak. When free() is called, the pointer must not be dereferenced again.

Note that get_string() must be declared or defined prior to main().

hmjd
  • 120,187
  • 20
  • 207
  • 252
  • ups, yes i forgot that, it's just sample code but i'll correct it, thanks :) – pasadinhas May 12 '13 at 11:02
  • I can't edit it, must be a moderator. They say it's mostly code – pasadinhas May 12 '13 at 11:03
  • One more question. If i needed that `str` var untill the very end of `main`, should i free it anyway (just because I `malloc()` it)? – pasadinhas May 12 '13 at 11:05
  • 1
    Basically you don't have to, since the OS will free it anyway, but it is a good practice to free it, since you might in the future cut & paste it into some function, and forget to add `free()` there. – Elazar May 12 '13 at 11:36
  • 1
    @Miguel, see http://stackoverflow.com/questions/10223677/when-a-program-terminates-what-happens-to-the-memory-allocated-using-malloc-that – hmjd May 12 '13 at 13:22
2

You do not need to (MUST NOT) free the temp variable, but you need to free str in your main (as it's malloced in get_string).

nullptr
  • 11,008
  • 1
  • 23
  • 18