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.)
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 |
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.
#include <stdlib.h>
int main() {
int *array = malloc(10 * sizeof(int));
free(array);
}