Memory allocation in C

Static Memory Allocation:

 Memory is allocated for the declared variable by the compiler. The address can be obtained by using ‘address of’ operator and can be assigned to a pointer. The memory is allocated during compile time. Since most of the declared variables have static memory, this kind of assigning the address of a variable to a pointer is known as static memory allocation.

How Memory Management Works in C?

When you declare a variable using a basic data type, the C compiler automatically allocates memory space for the variable in a pool of memory called the stack.
For example, a float variable takes typically 4 bytes (according to the platform) when it is declared. We can verify this information using the sizeof operator as shown in below example
#include <stdio.h>
int main() { float x; printf("The size of float is %d bytes", sizeof(x)); return 0;}
The output will be:
 The size of float is 4 bytes 
Also, an array with a specified size is allocated in contiguous blocks of memory, each block has the size for one element:
#include <stdio.h>
int main() { float arr[10];
printf("The size of the float array with 10 element is %d", sizeof(arr)); return 0;} 
The result is:
 The size of the float array with 10 element is 40
As learned so far, when declaring a basic data type or an array, the memory is automatically managed. However, there is a process for allocating memory which will permit you to implement a program in which the array size is undecided until you run your program (runtime). This process is called "Dynamic memory allocation."

Dynamic memory allocation

Dynamic memory allocation is an aspect of allocating and freeing memory according to your needs. Dynamic memory is managed and served with pointers that point to the newly allocated space of memory in an area which we call the heap. Now you can create and destroy an array of elements at runtime without any problems.
To sum up, the automatic memory management uses the stack, and the dynamic memory allocation uses the heap.
The <stdlib.h> library has functions responsible for dynamic memory management.
FunctionPurpose
mallocAllocates the memory of requested size and returns the pointer to the first byte of allocated space.
callocAllocates the space for elements of an array. Initializes the elements to zero and returns a pointer to the memory.
reallocIt is used to modify the size of previously allocated memory space.
FreeFrees or empties the previously allocated memory space.
Let's discuss the above functions with their application

The malloc Function

The malloc() function stands for memory allocation. It is a function which is used to allocate a block of memory dynamically. It reserves memory space of specified size and returns the null pointer pointing to the memory location. The pointer returned is usually of type void. It means that we can assign malloc function to any pointer.
Syntax
ptr = (cast_type *) malloc (byte_size);
Here,
  • ptr is a pointer of cast_type.
  • The malloc function returns a pointer to the allocated memory of byte_size.
Example: ptr = (int *) malloc (50)
When this statement is successfully executed, a memory space of 50 bytes is reserved. The address of the first byte of reserved space is assigned to the pointer ptr of type int.
Consider another example:
#include <stdlib.h>
int main(){
int *ptr;
ptr = malloc(15 * sizeof(*ptr)); /* a block of 15 integers */
    if (ptr != NULL) {
      *(ptr + 5) = 480; /* assign 480 to sixth integer */
      printf("Value of the 6th integer is %d",*(ptr + 5));
    }
}
Output:
Value of the 6th integer is 480
  1. Notice that sizeof(*ptr) was used instead of sizeof(int) in order to make the code more robust when *ptr declaration is typecasted to a different data type later.
  2. The allocation may fail if the memory is not sufficient. In this case, it returns a NULL pointer. So, you should include code to check for a NULL pointer.
  3. Keep in mind that the allocated memory is contiguous and it can be treated as an array. We can use pointer arithmetic to access the array elements rather than using brackets [ ]. We advise to use + to refer to array elements because using incrementation ++ or += changes the address stored by the pointer.
Malloc function can also be used with the character data type as well as complex data types such as structures.

The free Function

The memory for variables is automatically deallocated at compile time. In dynamic memory allocation, you have to deallocate memory explicitly. If not done, you may encounter out of memory error.
The free() function is called to release/deallocate memory. By freeing memory in your program, you make more available for use later.
For example:
#include <stdio.h>
int main() {
int* ptr = malloc(10 * sizeof(*ptr));
if (ptr != NULL){
  *(ptr + 2) = 50;
  printf("Value of the 2nd integer is %d",*(ptr + 2));
}
free(ptr);
}
Output
 Value of the 2nd integer is 50

The calloc Function

The calloc function stands for contiguous allocation. This function is used to allocate multiple blocks of memory. It is a dynamic memory allocation function which is used to allocate the memory to complex data structures such as arrays and structures.
Malloc function is used to allocate a single block of memory space while the calloc function is used to allocate multiple blocks of memory space. Each block allocated by the calloc function is of the same size.
Syntax:
ptr = (cast_type *) calloc (n, size);
  • The above statement is used to allocate n memory blocks of the same size.
  • After the memory space is allocated, then all the bytes are initialized to zero.
  • The pointer which is currently at the first byte of the allocated memory space is returned.
Whenever there is an error allocating memory space such as the shortage of memory, then a null pointer is returned.
The program below calculates the sum of an arithmetic sequence.
#include <stdio.h>
    int main() {
        int i, * ptr, sum = 0;
        ptr = calloc(10, sizeof(int));
        if (ptr == NULL) {
            printf("Error! memory not allocated.");
            exit(0);
        }
        printf("Building and calculating the sequence sum of the first 10 terms \ n ");
        for (i = 0; i < 10; ++i) { * (ptr + i) = i;
            sum += * (ptr + i);
        }
        printf("Sum = %d", sum);
        free(ptr);
        return 0;
    }
Result:
 
Building and calculating the sequence sum of the first 10 terms
Sum = 45

calloc vs. malloc: Key Differences

The calloc function is generally more suitable and efficient than that of the malloc function. While both the functions are used to allocate memory space, calloc can allocate multiple blocks at a single time. You don't have to request for a memory block every time. The calloc function is used in complex data structures which require larger memory space.
The memory block allocated by a calloc function is always initialized to zero while in malloc it always contains a garbage value.

The realloc Function

Using the realloc() function, you can add more memory size to already allocated memory. It expands the current block while leaving the original content as it is. realloc stands for reallocation of memory.
realloc can also be used to reduce the size of the previously allocated memory.
Syntax
ptr = realloc (ptr,newsize);
The above statement allocates a new memory space with a specified size in the variable newsize. After executing the function, the pointer will be returned to the first byte of the memory block. The new size can be larger or smaller than the previous memory. We cannot be sure that if the newly allocated block will point to the same location as that of the previous memory block. This function will copy all the previous data in the new region. It makes sure that data will remain safe.
For example:
#include <stdio.h>
int main () {
   char *ptr;
   ptr = (char *) malloc(10);
   strcpy(ptr, "Programming");
   printf(" %s,  Address = %u\n", ptr, ptr);

   ptr = (char *) realloc(ptr, 20); //ptr is reallocated with new size
   strcat(ptr, " In 'C'");
   printf(" %s,  Address = %u\n", ptr, ptr);
   free(ptr);
   return 0;
} 
Whenever the realloc results in an unsuccessful operation, it returns a null pointer, and the previous data is also freed.

Dynamic Arrays

A Dynamic array allows the number of elements to grow as needed. They are widely used in Computer science algorithms.
in the following program, we create and resize an array dynamically
#include <stdio.h>
    int main() {
        int * arr_dynamic = NULL;
        int elements = 2, i;
        arr_dynamic = calloc(elements, sizeof(int)); //Array with 2 integer blocks
        for (i = 0; i < elements; i++) arr_dynamic[i] = i;
        for (i = 0; i < elements; i++) printf("arr_dynamic[%d]=%d\n", i, arr_dynamic[i]);
        elements = 4;
        arr_dynamic = realloc(arr_dynamic, elements * sizeof(int)); //reallocate 4 elements
        printf("After realloc\n");
        for (i = 2; i < elements; i++) arr_dynamic[i] = i;
        for (i = 0; i < elements; i++) printf("arr_dynamic[%d]=%d\n", i, arr_dynamic[i]);
        free(arr_dynamic);
    } 
Result at the screen:
 
arr_dynamic[0]=0
arr_dynamic[1]=1
After realloc
arr_dynamic[0]=0
arr_dynamic[1]=1
arr_dynamic[2]=2
arr_dynamic[3]=3

Summary

  • We can dynamically manage memory by creating memory blocks as needed in the heap
  • In dynamic memory allocation, memory is allocated at a run time.
  • Dynamic memory allocation permits to manipulate strings and arrays whose size is flexible and can be changed anytime in your program.
  • It is required when you have no idea how much memory a particular structure is going to occupy.
  • Malloc is a dynamic memory allocation function which stands for memory allocation that blocks of memory with the specific size initialized to a garbage value
  • Calloc is a contiguous memory allocation function that allocates multiple memory blocks at a time initialized to 0
  • Realloc is used to reallocate memory according to the specified size.
  • Free function is used to clear the dynamically allocated memory.

No comments:

Post a Comment

Featured Post

Core and Advance Python

                      Language Fundamentals