C Memory Allocation

Memory allocation is a crucial aspect of programming.
There are two ways

  1. Static Memory Allocation
  2. Dynamic Memory Allocation

Static Memory Allocation

It's done at a compile-time.
The size of the memory is determined before the program is executed.

Example
#include <stdio.h>

int main() {
    int x = 10; // Variable x is allocated on the stack
    // ...
    return 0;
}

Variables declared within a function are typically allocated on the stack.
The memory is automatically released when the function exits.


Dynamic Memory Allocation

It's done at runtime and allows for flexible memory management.
Performed using the functions malloc, calloc, realloc, and free from the <stdlib.h> library.

Functions

Description

Example

malloc

Memory Allocation: Allocates a block of memory for an array of 5 integers.

int *dynamicArray = (int *)malloc(5 * sizeof(int));

calloc

Contiguous Memory Allocation: Allocates contiguous block of memory for an array of 5 integers and initializes them to zero.

int *dynamicArray = (int *)calloc(5, sizeof(int));

realloc

Reallocation: Changes the size of the previously allocated memory block (here, resizing to space for 10 integers).

dynamicArray = (int *)realloc(dynamicArray, 10 * sizeof(int));

free

Memory Deallocation: Releases the memory allocated by malloc, calloc, or realloc

free(dynamicArray);


Example
#include <stdio.h>
#include <stdlib.h>

int main() {
    // Dynamic memory allocation for an integer
    int *dynamicInt = (int *)malloc(sizeof(int));
    *dynamicInt = 42;

    printf("Dynamic Integer: %d\n", *dynamicInt);

    // Dynamic memory allocation for an array of integers
    int *dynamicArray = (int *)malloc(5 * sizeof(int));
    for (int i = 0; i < 5; i++) {
        dynamicArray[i] = i * 10;
    }

    printf("Dynamic Array: ");
    for (int i = 0; i < 5; i++) {
        printf("%d ", dynamicArray[i]);
    }
    printf("\n");

    // Freeing dynamically allocated memory
    free(dynamicInt);
    free(dynamicArray);

    return 0;
}

Quick Recap - Topics Covered

C Memory allocation
Static Memory Allocation
Dynamic Memory Allocation

Practice With Examples in Compilers

The Concepts and codes you leart practice in Compilers till you are confident of doing on your own. A Various methods of examples, concepts, codes availble in our websites. Don't know where to start Down some code examples are given for this page topic use the code and compiler.


Example 1
Example 1 Example 2 Example 3 Example 4 Example 5


Quiz


FEEDBACK