If I allocate memory to a pointer which has been declared inside of a function as static, and don't free() it, is that memory freed when the function returns?

8 Years
Discussion Span
Last Post by Duoas


Automatic variables are freed:

int foo()
  int a = 42;
  int* p = (int*)malloc( sizeof( int ) );

  *p = a;

  return a;

Once foo() returns, the automatic variables a (an int) and p (a pointer) are freed, but the heap variable created on line four still exists.

Remember, malloc() creates stuff that has no name. We only have its address (stored in the variable p). By dereferencing p we can access that unnamed value: printf( "%d\n", *p ); Every time you create something on the heap, you must also explicitly free() it.

Here's another example that might help:

#include <stdio.h>
#include <stdlib.h>

int main()
  int* p;
  p = (int*)malloc( sizeof( int ) );
  *p = 42;

  printf( "The address of the local (automatic) variable p is %p\n", &p );
  printf( "The address of the heap variable is %p\n\n", p );

  printf( "The value of the local variable is %08X (%d)\n",  p,  p );
  printf( "The value of the heap variable is %08X (%d)\n",  *p, *p );

  free( p );
  return 0;

Notice that p's value is the address (or location) of the heap variable.

Hope this helps.

Oh, and a static local variable is just another way of making a global automatic variable. So

int next_foo()
  static int my_foo = 0;
  return ++my_foo;

is very much the same as

int my_foo = 0;
int next_foo()
  return ++my_foo;

The only difference is whether my_foo can be seen outside of next_foo().

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.