This month we’re going to examine a topic that is probably familiar to those of you who have any experience with programming — dynamic memory allocation. In any programs of significant heft, dynamic memory management is a necessity. You are probably experienced with the standard C functions malloc() and free(), and we’ll do a brief recap of those memory allocation and deallocation functions. Following that, we will look at how memory allocation in Linux actually works.
This month we’re going to examine a topic that is probably familiar to those of you who have any experience with programming — dynamic memory allocation. In any programs of significant heft, dynamic memory management is a necessity. You are probably experienced with the standard C functions malloc() and free(), and we’ll do a brief recap of those memory allocation and deallocation functions. Following that, we will look at how memory allocation in Linux actually works.
Memory Allocation Functions
There are three standard C functions that you can use to allocate memory — malloc() , calloc() , and realloc() . Their prototypes, as defined in <stdlib.h> , are:
malloc() is the simplest of the allocators. It simply takes an argument specifying the size of the memory block that you wish to allocate and returns a pointer to a block of memory of that size. calloc() takes in two arguments, a number of elements ( nmemb ), and a size for each element ( size ). The total size allocated by a call to calloc() will be (nmemb * size) bytes. Also, calloc() actually sets all the memory it returns to NULL . In contrast, there are no guarantees regarding the values stored in the memory returned my malloc() .
realloc() is used to reallocate a section of memory that has been previously allocated. Notice that…
Please log in to view this content.
Not Yet a Member?
Register with LinuxMagazine.com and get free access to the entire archive, including: