Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does going out of scope like this free the associated memory?

Tags:

c

memory

malloc

I was just wondering, in the following scenarion, is the memory used by 'stringvar' freed after method1 is done executing?

// Just some method
void method2(char* str)
{
  // Allocate 10 characters for str
  str = malloc(10 * sizeof(char));
}

// Just another method
void method1()
{
  char* stringvar;
  method2(stringvar);

  // Is the memory freed hereafter, or do I need to call free()?
}

I ask, because if I put a 'free(stringvar)' at the end of method1, I get a warning that stringvar is unitialized inside method1 (which is true).

like image 353
pbean Avatar asked Nov 28 '22 05:11

pbean


1 Answers

No, the memory is not deallocated after method1, so you'll have a memory leak. Yes, you will need to call free after you're done using the memory.

You need to send a pointer to a pointer to method2 if you want it to allocate memory. This is a common idiom in C programming, especially when the return value of a function is reserved for integer status codes. For instance,

void method2(char **str) {
    *str = (char *)malloc(10);
}

char *stringvar;
method2(&stringvar);
free(stringvar);
like image 57
Andrew Keeton Avatar answered Nov 29 '22 18:11

Andrew Keeton