Guides:C/C Crash Course/Dynamic Memory Allocation

From CoderGuide

Jump to: navigation, search

Back to TOC

Dynamic Memory Allocation

Where pointers come in handy, besides speeding up functions calls when passing structures to functions, is when we start dealing with dynamic memory allocation. That is, our program can allocate memory, and create any size array we want to (just as long as there is enough memory in the system to allocate that much).

It is also very important that you unallocated, or free, whatever memory you allocated for use by your program, especially when that data will no longer be used. Failure to do so can make some operating systems unstable, and causes a program bug known as "Memory Leaks", where memory is essentially lost by the program.

Here is an example of how to allocate memory (these functions are defined in stdlib.h):


/*******
NULL is a defined value of a zero/null pointer.  Its definition looks
something like this:
 
#define NULL ((void *)0)
 
*****/
 
char *string;
 
/*allocate space for a character array of 2048 elements*/
string=malloc((sizeof (char)*2048);
 
 
if(string==NULL) puts("Couldn't allocate memory");
else free(string); /*free allocated space */
 
string=calloc(2048, sizeof (char)); /*same as above*/
 
if(string==NULL) puts("Couldn't allocate memory");
else free(string); /*free allocated space */

If memory allocation fails, the returned pointer is NULL to indicate a failure. It is a good idea to set any pointer that is not pointing to a valid place in memory to NULL (or 0) so your program can know right away if it should use that pointer or not. This is very handy for arrays of pointers.

calloc() differs from malloc() in that calloc will zero out the memory before use, while malloc is not required to. For that reason calls to malloc() are often faster than calls to calloc().

Personal tools