Malloc()Can Also Avoid System Calls by Utilisingfast Bins. 6

Malloc()Can Also Avoid System Calls by Utilisingfast Bins. 6

TheC programming languagemanages memorystatically,automatically, ordynamically. Static-duration variables are allocated in main memory, usually along with the executable code of the program, and persist for the lifetime of the program; automatic-duration variables are allocated on thestackand come and go as functions are called and return. For static-duration and automatic-duration variables, the size of the allocation must becompile-timeconstant (except inC99, which allowed variable-length automatic arrays[5]). If the required size is not known untilrun-time(for example, if data of arbitrary size is being read from the user or from a disk file), then using fixed-size data objects is inadequate.

The lifetime of allocated memory can also cause concern. Neither static- nor automatic-duration memory is adequate for all situations. Automatic-allocated data cannot persist across multiple function calls, while static data persists for the life of the program whether it is needed or not. In many situations the programmer requires greater flexibility in managing the lifetime of allocated memory.

These limitations are avoided by usingdynamic memory allocationin which memory is more explicitly (but more flexibly) managed, typically, by allocating it from thefree store(informally called the "heap"), an area of memory structured for this purpose. In C, the library functionmallocis used to allocate a block of memory on the heap. The program accesses this block of memory via apointerthatmallocreturns. When the memory is no longer needed, the pointer is passed tofreewhich deallocates the memory so that it can be used for other purposes.

malloc()can also avoid system calls by utilisingfast bins.[6]

Some platforms provide library calls which allow run-time dynamic allocation from the C stack rather than the heap (e.g.alloca()[7]). This memory is automatically freed when the calling function ends.

Overview of functions[edit]

The C dynamic memory allocation functions are defined instdlib.hheader (cstdlibheader in C++).[1]

Function / Description
malloc / allocates the specified number of bytes
realloc / increases or decreases the size of the specified block of memory. Reallocates it if needed
calloc / allocates the specified number of bytes and initializes them to zero
free / releases the specified block of memory back to the system

Differences betweenmalloc()andcalloc()[edit]

There are two differences between these functions. First,malloc()takes a single argument (the amount of memory to allocate in bytes), whilecalloc()needs two arguments (the number of variables to allocate in memory, and the size in bytes of a single variable). Secondly,malloc()does not initialize the memory allocated, whilecalloc()guarantees that all bytes of the allocated memory block have been initialized to zero.

Usage example[edit]

Creating anarrayof ten integers with automatic scope is straightforward in C:

int array[10];

However, the size of the array is fixed at compile time. If one wishes to allocate a similar array dynamically, the following code can be used:

int* array =malloc(10*sizeof(int));

This computes the number of bytes that ten integers occupy in memory, then requests that many bytes frommallocand assigns the result to apointernamedarray(due to C syntax, pointers and arrays can be used interchangeably in some situations).

Becausemallocmight not be able to service the request, it might return anull pointerand it is good programming practice to check for this:

int* array =malloc(10*sizeof(int));

if (NULL== array) {

fprintf(stderr, "malloc failed\n");

return(-1);

}

When the program no longer needs the dynamic array, it should callfreeto return the memory it occupies to the free store:

free(array);

The memory set aside bymallocis notinitializedand may containcruft: the remnants of previously used and discarded data. After allocation withmalloc, elements of the array areuninitialized variables. The commandcallocwill allocate and clear the memory in one step:

int* array =calloc(10, sizeof (int));

allocates a region of memory large enough to hold 10 integers, and sets to zero all the bytes within that memory space.