C dynamic memory allocation

memory management

In the C programming language, dynamic memory allocation refers to allocating memory during a program's run time. Dynamically allocated memory is obtained from a storage pool called a heap. A group of functions in the C standard library are typically used for dynamic memory allocation.

Overview of functions

change

C dynamic memory allocation functions are defined in stdlib.h header.

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

Differences between malloc and calloc

change
  • malloc takes a single argument (the amount of memory to allocate in bytes), while calloc needs two arguments (the number of variables to allocate in memory, and the size in bytes of a single variable).
  • malloc does not initialize the memory allocated, while calloc guarantees that all bytes of the allocated memory block have been initialized to 0.

Bugs and security implications

change

The C language does not by default check that the calls to these functions, or the accesses to the arrays they create, are used correctly. If the program does something invalid, such as accessing memory beyond what has been allocated, or using memory that has been freed, this can cause the program to crash or to behave in some other undesirable way. In some cases, improper use of these functions can create security vulnerabilities that allow hackers to read or modify sensitive data or run malicious code.

Example code

change
#include <stdlib.h>
int main() {
    int *array = malloc(10 * sizeof(int));
    free(array);
}