The heap – malloc() and free()

I don’t want to delve too deep into pointers in C. But here’s some additional information on the two most commonly used functions associated with heap memory – malloc() and free().

malloc()

The malloc() function takes as its argument an unsigned integer which represents the size of the memory block requested from the heap (in bytes). Then malloc() returns a pointer to a new heap block if the process is successful., and NULL otherwise (usually because the heap is full). An easy way of calculating the number of bytes needed is by using the sizeof() function. For example, sizeof(int), will return the size, in bytes of an int.

free()

The function free() takes a pointer to a heap block, and returns it to the free pool for reuse later. The pointer that is the argument to free() must be the same one returned earlier by malloc(). There is no requirement for providing the size of the heap block, the memory manager will deal with this. Failure to deallocate memory in programs where the use of the heap is prolific can result in memory leaks, and nasty thing happening.

An example

void BadHeap() 
{
    // allocate the pointer, but not the pointer
    int *p;
    // this dereference is a serious runtime error
    *p = 42; 
    // this will cause a Segmentation fault
    printf("%d\n",*p);
}

Compare this with the proper way of doing things:

void GoodHeap() 
{
    // allocate the pointer
    int *p;
    // allocate heap memory to the pointer
    p = malloc(sizeof(int));
    // allocate a value to the heap memory
    *p = 42;
    // print out the value 
    printf("%d\n", *p);
    // free the allocated memory
    free(p);
}

If you like this, there is more fun to be had with calloc(), valloc(), and realloc().

 

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s