Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is the memory of a (character) array freed by going out of scope?

Tags:

arrays

c

memory

Very much related to my previous question, but I found this to be a separate issue and am unable to find a solid answer to this.

Is the memory used by a (character) array freed by going out of scope?

An example:

void method1()
{
  char str[10];
  // manipulate str
}

So after the method1 call, is the memory used by str (10 bytes) freed, or do I need to explicitly call free on this as well?

My intuition tells me this is just a simple array of primitive types, so it's automatically freed. I'm in doubt because in C you can't assume anything to be automatically freed.

like image 979
pbean Avatar asked Aug 26 '09 14:08

pbean


1 Answers

In this case no you do not need to call free. The value "str" is a stack based value which will be cleaned up when that particular method / scope is exited.

You only need to call free on values which are explicitly created via malloc.

like image 147
JaredPar Avatar answered Oct 02 '22 03:10

JaredPar