When the free() is necessary?

At the C literature, there are many scenarios when free() is necessary to avoid memory leakage.
I would like to hear from you when the free() is really necessary at the Arduino IDE.

For instance, when I create a char array, such as “char StringFinal[40];”, do I need to “free(StringFinal)” after using it? Naturally, the same question also goes for any variable of other datatype which I used and I will not use anymore.

Finally, do I need to do this for local variables at functions also?


You free things which you have malloc'd. So, no, you don't free char arrays, that would cause a crash. You don't free local variables either.


void setup () 
 Serial.begin (115200);
}  // end of setup

void loop () {

 char * p = (char *) malloc (100);  // give me 100 bytes

 strcpy (p, "Nick Gammon");

 Serial.println (p);

 free (p);  // release memory used by p

}  // end of loop

The only thing I freed was variable "p" which was the one which I did a malloc on.

If you run that it prints "Nick Gammon" indefinitely. Now comment out the "free" line and it prints it around 20 times, which is what you expect, as it has used up the 2000 bytes of free memory with 20 lots of malloc (100).

In fact there is a slight overhead for malloc, as it has to remember how big the blocks are (notice you don't do "free (100)"). Also it has to link blocks together so it knows where the next one is.

Thank you Nick. Very good explanation.

One question: if instead of

char * p = (char *) malloc (100);  // give me 100 bytes

I use

char p[100];

what changes? Do I still need to free (I believe not because it was not malloc'ed)? So is it a better programming approach?


No, you don't need to free. That memory is allocated by the compiler "statically" or "automatically" (depending on whether or not the declaration is inside a function). In neither case do you need to free it.

Basically remember that, you free things which you malloc. If and only if. No malloc, no free.

So is it a better programming approach?

A lot depends on what you need to do. Say you have a single string, and you know in advance how long it is going to be. Then this is fine:

char p [100];

But what if you don't know in advance its size? Then you have a problem. You might allocate a big number, but either it may still be too small, or you are wasting memory (bearing in mind you only have around 2048 bytes to start with).

Another case for dynamic allocation is where you may need more than one batch of it. For example, in a game you might have between 1 and 10 monsters. So you dynamically allocate (malloc) for each monster, and get the memory back (free) when it dies. Something like that.