int a = 42;
int* p = (int*)malloc( sizeof( int ) );
*p = 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:
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 );
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
static int my_foo = 0;
is very much the same as
int my_foo = 0;
The only difference is whether my_foo can be seen outside of next_foo().