C dynamic memory allocation
In the C programming language, many of the commands in a program change the memory of the computer running that program. The memory comes in different ways, with some memory always made available to every part program, some memory given over to the functions and code blocks in the program, and some memory which can be given to the program as it needs it, and freed up when the need has finished. This memory that is allocated to the program and freed later is known as dynamic memory. (The other types are known as static memory and automatic memory.)
The 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 | change source]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 | change source]- 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 | change source]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 | change source]#include <stdlib.h>
int main() {
int *array = malloc(10 * sizeof(int));
free(array);
}