Array Lifetimes in C

File.c:
  int [] function() {
         int myArray[10];       // allocates 10 integers on STACK
                                        // do some processing with array
         return myArray;        // the startaddress of the memory
                                // ON THE STACK is copied back to caller
  }

  int someArray[] = function();  // gets a stack address back (where myArray 
                                 // USED TO START). This memory is NO LONGER
                                 // allocated to function() or caller and can be 
                                 // re-used anytime.

When the call to function() returns becomes the local variable myArray AND the associated array memory invalid. But the address of this memory has been copied back to the caller and stored in the array variable someArray. This means that the memory allocated in function() is STILL REACHABLE from someArray. Unfortunately the memory is no longer allocated and can be re-used during the next function call. The caller has received a reference to invalid memory.

It is possible in C to allocate the array memory on the HEAP just like in Java. We will compare the performance of stack vs. heap allocation below. For now just look at a correct array allocation:

File.c:
  int [] function() {
     int myArray[] = malloc(sizeof(int)*10); // allocates 10 integers on HEAP 
                           // do some processing with array
     return myArray;       // the startaddress of the memory
                           // ON THE HEAP is copied back to caller
  }

  int someArray[] = function();  // gets a HEAP address back (where myArray 
                                 // starts). This memory is still 
                                 // allocated but ownership has been 
                                 // transferred SILENTLY to someArray. 

Note

Note that the OWNERSHIP of the memory changed. The caller MUST release the allocated memory when it is no longer used. Otherwise a "memory leak" happens and the piece of memory from the heap is lost to the program. It stays allocated but if someArray is thrown away without a "free(somearray);" call then nobody can reach the memory anymore. Unlike Java C has no garbage collector looking out for those orphans and collecting them. Memory management is the programmers responsibility.