- A Word on C
- Comment Tokens
- Code Bodies
- Variable Scope
- Built-In Functions
- Memory Management
- Dynamic Memory Allocation
- Memory Leaks
- Definitions and Macros
- Conclusion
- Next Steps
Dynamic Memory Allocation
The area of memory known as the heap that is available to applications is managed by using built-in functions provided by C for dynamic memory allocation.
The heap is an area of memory, separate from the stack, which is available for program use. Nothing automatically happens to heap memory as it does to the stack with frames added and removed constantly; this makes the heap a preferred memory location for data and structures with a life span greater than a single function.
Only heap memory can be dynamically allocated and freed using the built-in functions for memory management.
To dynamically allocate memory, C provides several functions. The first to consider is the function malloc.
malloc (Memory Allocation)
The allocation function malloc reserves a block of uninitialized memory from the heap in the size specified.
char *buf; buf = malloc( sizeof(char) * 10 ); // space for 10 characters
If the function malloc is not able to reserve the requested memory, it returns NULL. Testing the return of the function ensures that a valid memory block exists and diverts a program crash.
if( buf == NULL ) { printf( "Fatal Error: Failed to malloc memory" ); exit( 1 ); }
The allocation of buf in the previous example is equivalent to
char buf[10];
except that the memory returned from the malloc is heap memory and will exist after the function containing the allocation returns. This complicates memory management slightly because any memory allocated from the heap must be explicitly returned to the heap when the program is finished with it.
To return memory to the heap, making it available for subsequent allocations, C provides the function free.
free (Returning Allocated Memory)
Every block of memory dynamically allocated should have a corresponding free.
When you fail to free memory that is dynamically allocated within a program, you have caused a memory leak. Memory leaks cause programs to suffer in performance as well as face a potential failure.
The memory associated with a program grows in direct proportion to the size of the program's heap.
A program that never returns memory to the heap continues to grow in size until no further growth is possible; either the system runs out of memory or a maximum program size is reached, at which time further calls to malloc fail. Also, the greater the amount of memory consumed by a program the slower its execution.
The syntax for performing a free follows the form
free( (char *)mem );
where mem is the memory gained by a dynamic allocation function such as malloc.
Note
The function free expects a parameter of the char * type to be passed to it. Because the function is used to return the allocation of any type of data to the heap, it is often necessary to cast the memory being returned to a pointer of the proper type (char *).
Table 3.4 shows several functions provided by C for performing dynamic memory allocation.
Table 3.4 Memory Allocation Functions
Function |
Example |
Description |
malloc |
memPtr = malloc( size ); |
Returns a pointer to an unitialized block of memory; where size is the size of the block, for example, (sizeof(data type) * count ) |
calloc |
arrayPtr = calloc( size, num_ele ); |
Returns a pointer to an array initialized to 0, with num_ele (number of elements) of the specified size |
realloc |
memPtr = realloc( memPtr, new_size ); |
Expands an existing block of memory to a new_size; current contents of memPtr are transferred to the expanded block |
strdup |
char *newStr = strdup ( "Abcde" ); |
Duplicates a string; constitutes a memory allocation function because the results of strdup must be explicitly freed |
Let me give you a final word of caution for developing proper memory management skills: Care for the relationship of automatic variables placed on the stack and references to dynamically allocated memory, which at some point must be returned to the heap.