6.12. Memory Management

Up to this point, all the variables you have created have been stored in a part of memory known as the stack. The stack is a contiguous block of memory, meaning that it forms one continuous segment unbroken by gaps. Whenever a function is entered, the local variables declared there are pushed onto the end of the stack. When the function returns, the variables are popped off the stack again, effectively destroying them.

Stack variables can't be used for every situation, so C also gives you access to another part of memory for storing variables called the heap or free store. When you put a variable on the heap, you are responsible for managing its memory yourself. In other words, you have to request that the memory be assigned to the variable, and you are also responsible for freeing the memory when you are finished with it. If you don't do this, you can end up with a memory leak, where the amount of memory used by your program rises over time, perhaps even causing your computer to slow or crash.

Variables that have their values stored on the heap are always pointers. They point to the location in memory where the data is stored. Here is an example of creating and freeing a heap variable:

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

int main() {
    float *heapVar;
    heapVar = malloc( sizeof(float) );

    *heapVar = 4.0;
    printf( "%f\n", *heapVar );

    free(heapVar);

    return 0;
}

The variable heapVar is declared as a pointer, and then assigned to the return value of the function ...

Get Beginning Mac OS® X Programming now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.