C programming - memory allocation

In C programming, memory allocation refers to the process of reserving a block of memory for storing data during program execution. C provides several ways to allocate memory, including static allocation, automatic allocation, and dynamic allocation.

  1. Static Allocation: Static allocation is a way of allocating memory at compile-time, and the allocated memory remains fixed throughout the program's lifetime. In static allocation, the memory is allocated for the variable during program execution. To allocate memory statically, we use the following syntax:
r‮fe‬er to:theitroad.com
<data_type> <variable_name> = <initial_value>;

For example, to statically allocate an integer variable x with an initial value of 10, we can write:

int x = 10;
  1. Automatic Allocation: Automatic allocation is a way of allocating memory at runtime, and the allocated memory is automatically released when the variable goes out of scope. In automatic allocation, the memory is allocated on the stack. To allocate memory automatically, we use the following syntax:
<data_type> <variable_name>;

For example, to automatically allocate an integer variable x, we can write:

int x;
  1. Dynamic Allocation: Dynamic allocation is a way of allocating memory at runtime, and the allocated memory remains available until it is explicitly released by the program. In dynamic allocation, the memory is allocated on the heap using library functions such as malloc(), calloc(), and realloc(). To allocate memory dynamically, we use the following syntax:
<data_type> *<variable_name> = (<data_type> *) malloc(<size_in_bytes>);

For example, to dynamically allocate an integer variable x with a size of 4 bytes, we can write:

int *x = (int *) malloc(sizeof(int));

After allocating memory dynamically, we can access and manipulate the memory using the pointer variable x. Once the memory is no longer needed, we can release it using the free() function as follows:

free(x);