[edit]Memory Management
In C, you have already considered creating variables for use in the program. You have created some arrays for use, but you may have already noticed some limitations:
§ the size of the array must be known beforehand
§ the size of the array cannot be changed in the duration of your program
Dynamic memory allocationin C is a way of circumventing these problems.
[edit]Malloc
#include <stdlib.h>
void *calloc(size_t nmemb, size_t size);
void free(void *ptr);
void *malloc(size_t size);
void *realloc(void *ptr, size_t size);
The C functionmallocis the means of implementing dynamic memory allocation. It is defined in stdlib.h or malloc.h, depending on what operating system you may be using. Malloc.h contains only the definitions for the memory allocation functions and not the rest of the other functions defined in stdlib.h. Usually you will not need to be so specific in your program, and if both are supported, you should use <stdlib.h>, since that is ANSI C, and what we will use here.
The corresponding call to release allocated memory back to the operating system isfree.
When dynamically allocated memory is no longer needed,freeshould be called to release it back to the memory pool. Overwriting a pointer that points to dynamically allocated memory can result in that data becoming inaccessible. If this happens frequently, eventually the operating system will no longer be able to allocate more memory for the process. Once the process exits, the operating system is able to free all dynamically allocated memory associated with the process.
Let's look at how dynamic memory allocation can be used for arrays.
Normally when we wish to create an array we use a declaration such as int array[10];
Recallarraycan be considered a pointer which we use as an array. We specify the length of this array is 10ints. After array[0], nine other integers have space to be stored consecutively.
Sometimes it is not known at the time the program is written how much memory will be needed for some data. In this case we would want to dynamically allocate required memory after the program has started executing. To do this we only need to declare a pointer, and invoke malloc when we wish to make space for the elements in our array,or, we can tell malloc to make space when we first initialize the array. Either way is acceptable and useful. Previous Page|Next Page