C dynamic memory allocation
Created By: chatGPT
Dynamic memory allocation in C allows you to request memory at runtime, using pointers to manage memory efficiently. The standard library provides several functions to facilitate this, including
malloc
, calloc
, realloc
, and free
. Understanding how to allocate and deallocate memory is crucial for creating flexible and efficient programs.The
malloc
function is used to allocate a specific number of bytes and returns a pointer to the first byte of the allocated memory.void *malloc(size_t size);
To allocate memory for an array of integers, for example, you can do the following:
int *arr;
arr = (int *)malloc(n * sizeof(int));
If the allocation fails,
malloc
returns NULL. It is important to check this to avoid subsequent crashes when accessing allocated memory.if (arr == NULL) {
// handle allocation failure
}
The
calloc
function is similar to malloc
but additionally initializes the allocated memory to zero.void *calloc(size_t num, size_t size);
To use
calloc
for allocating memory for an array:int *arr;
arr = (int *)calloc(n, sizeof(int));
The
realloc
function can change the size of previously allocated memory. This can be useful if you need more space than originally allocated.void *realloc(void *ptr, size_t new_size);
Example of using
realloc
to resize an array:int *new_arr;
new_arr = (int *)realloc(arr, new_size * sizeof(int));
if (new_arr == NULL) {
// handle failure, old memory still valid
} else {
arr = new_arr; // point to new memory
}
Finally, it is essential to free allocated memory using the
free
function to prevent memory leaks. Always ensure that you free any memory you no longer need.void free(void *ptr);
Example of freeing allocated memory:
In summary, dynamic memory allocation is a powerful feature in C that allows for flexibility in how you manage memory. Properly using free(arr);
arr = NULL; // Optional but good practice
malloc
, calloc
, realloc
, and free
ensures efficient memory usage and program stability.