The easiest thing to remember is this: For each malloc() you should have a free(). That's not bulletproof but it's generally the right thing to do.
When you're asking about freeing local variables, I'm not sure what precisely you mean. If you asked for memory via malloc(), then yes, free it when you're done. Perhaps in the same function, or if you need to use the memory longer, whenever is most convenient. This is correct (assume malloc() succeeds):
Code:
void f(void)
{
char *x;
x = malloc(some_length);
snprintf(x, some_length, "foo%s", some_string);
free(x);
}
But you wouldn't do this:
Code:
void f(void)
{
char x[50];
free(x);
}
This is bad because you never allocated x yourself. When the function exits, x will be destroyed automatically. That's what happens with local (or more precisely, automatic) variables.
A memory leak is when you forget to free something; often as a result of "losing" the pointer:
Code:
void f(void)
{
char *x;
x = malloc(50);
x = NULL;
/* oops.. can't free the 50 bytes now */
}