C dynamic memory allocation

In a program written in the C programming language, information that the program is working on is stored in memory. The memory comes in different ways. One way is when the memory is always made available to every part program, known as global memory. Another way is to have memory inside the functions, known as automatic memory. There's static memory within the files of code . And then there's the way that this article is about, dynamic memory. With dynamic memory, the program can take memory as it needs it, and once the program has finished what it needs to, the memory is freed up and given back. The program can take a lot of memory or a little, depending on a need that might not be fully known when the program was written.

The dynamic memory allocation refers to when the program calls a function that sets aside some memory for the program to use - the memory is allocated to it.. Dynamically allocated memory is obtained from a storage pool called a heap. A group of functions in the C standard library are often used for dynamic memory allocation. (Different systems and programs can have variants of these.)

Overview of the usual functions for dynamic memory

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

Function Description
malloc allocates the specified number of bytes, and returns a pointer to that memory. If there wasn't enough, it returns NULL.
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

  • 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

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 wrong way. In some cases, dynamic memory allocation can be abused to create security vulnerabilities that allow hackers to read or modify sensitive data or run malicious code.

Example code

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