Memory Allocation

Usage of 'malloc', 'calloc', 'realloc', etc. functions in C.

Memory Allocation

Dynamic memory allocation refers to the method of allocating a block of memory and releasing it when the memory is not required at the time of running the program. A block of memory can be used to store values of simple or subscripted variables and a block of memory can be accessed using a pointer. Following are the functions used in dynamic memory allocation, and these functions are available in the header file <alloc.h>.

* "alloc.h" is a non-standard header file.

You can allocate memory dynamically using the 'malloc', 'calloc', and 'realloc' functions. Dynamic memory allocation allows you to allocate memory during runtime, and it's particularly useful when you don't know the exact size of the data you need to store at compile time.

malloc (Memory Allocation):

The 'malloc()' function is used to allocate a single block of memory to store values of specific data types. It also assigns the address of the first byte of the allotted space to a pointer.

  • Syntax:

void* malloc(size_t size);

  • Example:

int* intArray = (int*)malloc(5 * sizeof(int));
if (intArray == NULL) {
    // Check if malloc failed to allocate memory
    // Handle the error
}

calloc (Contiguous Allocation):

The 'calloc()' function is used to allocate memory in multiple blocks of the same size during the program execution. The space allocated is used to store the values of an array or structure.

  • Syntax:

void* calloc(size_t numElements, size_t elementSize);

  • Example:

int* intArray = (int*)calloc(5, sizeof(int));
if (intArray == NULL) {
    // Check if calloc failed to allocate memory
    // Handle the error
}

realloc (Reallocate Memory):

The 'realloc()' function is used to modify or reallocate the memory space that is previously allotted.

  • Syntax:

void* realloc(void* ptr, size_t newSize);

  • Example:

int* resizedArray = (int*)realloc(intArray, 10 * sizeof(int));
if (resizedArray == NULL) {
    // Check if realloc failed to allocate memory
    // Handle the error
} else {
    intArray = resizedArray;
}

Note: After you've finished using dynamically allocated memory, it's important to release it to prevent memory leaks. You can do this with the 'free()' function.

free() Function:

The 'free()' function is used to deallocate memory that was previously allocated dynamically using functions like 'malloc()', 'calloc()', or 'realloc()'. Dynamic memory allocation is a way to allocate memory on the heap, which allows you to manage memory at runtime. However, it's crucial to release this memory when it is no longer needed to prevent memory leaks.

The 'free()' function takes a single argument, which is a pointer to the dynamically allocated memory block that you want to deallocate. Here's the basic syntax of the 'free()' function:

  • Syntax:

void free(void *ptr);

Here's an example of how to use 'malloc()' and 'free()' to dynamically allocate and deallocate memory in C:

c Copy Code
#include <stdio.h>
#include <stdlib.h>

int main() {
    // Allocate memory for an integer
    int *ptr = (int *)malloc(sizeof(int));

    if (ptr == NULL) {
        printf("Memory allocation failed\n");
        return 1;
    }

    // Assign a value to the memory
    *ptr = 42;

    // Print the value stored in the allocated memory
    printf("The value stored in the memory is: %d\n", *ptr);

    // Deallocate the memory
    free(ptr);

    return 0;
}
Output:
The value stored in the memory is: 42

* This demonstrates that you allocated memory for an integer, stored the value 42 in it, and then successfully deallocated the memory using 'free()' function.

* Dangling pointers and memory leaks happen due to improper memory management in C.

Dangling Pointer:

A dangling pointer in C is a pointer that continues to point to a memory location after the memory it references has been deallocated or freed. Accessing a dangling pointer can lead to undefined behavior.

int *ptr = (int *)malloc(sizeof(int));
free(ptr);
// ptr is now a dangling pointer
*ptr = 5; // Accessing a freed memory location
  • Dangling pointers typically occur when a pointer continues to hold a reference to a memory location after the memory it points to has been deallocated or freed using functions like 'free()'.
  • This can happen when a pointer is not updated or set to 'NULL' after the memory it points to is released. Pointers that are not modified or validated after freeing the memory can still contain the old memory address, leading to a dangling pointer.

Memory Leak:

A memory leak in C occurs when dynamically allocated memory is not properly deallocated, causing your program to lose access to that memory. This unreleased memory can accumulate over time and lead to inefficient resource usage.

void someFunction() {
    int *ptr = (int *)malloc(sizeof(int));
    // Memory is allocated but never freed
}
  • Memory leaks occur when dynamically allocated memory is not properly deallocated using functions like 'free()'.
  • This can happen due to various reasons, such as forgetting to call 'free' on a previously allocated pointer, losing all references to allocated memory, or not reaching the deallocation code due to program flow (e.g., early return from a function).
  • Over time, memory leaks can accumulate, leading to a depletion of available memory resources and potential program instability.

Note: Both of these issues are common in C because the language places the responsibility for memory management on the programmer. Proper handling of pointers and memory allocation is essential to prevent these problems and ensure efficient and reliable code.

What's Next?

We actively create content for our YouTube channel and consistently upload or share knowledge on the web platform.