My notes on dynamic memory allocation in C

Dynamic Memory Allocation: Process in which the size of the data structure can be changed at run time.

4 Library functions:

  • malloc
  • calloc
  • realloc
  • free
Header File: <stdlib.h>

malloc: stands for memory allocation.
Reserves a block of memory of the specified number of bytes. It returns a pointer of type void which can be casted into any type.
ptr = (cast-type*) malloc(byte-size);
If space is insufficient, allocation fails and returns a NULL pointer.

calloc: stands for contiguous allocation.
malloc allocates a single block of memory,  whereas calloc allocates multiple blocks of memory and initializes them to zero.

ptr = (cast-type*)calloc(n, element-size);

free: free the memory allocated using malloc and calloc.
free(ptr);

realloc: Change the size of previously existing memory using realloc function
ptr = realloc(ptr, x);
Here ptr is reallocated with new size 'x'

malloc vs calloc:

1. Initialization: malloc does not initialize the allocated memory. calloc initializes it to zero
2. Number of arguments: calloc takes two arguments: 1) Number of blocks to be allocated 2) size of each block

It is better to use malloc over calloc, unless we want zero-initialization because malloc is faster than calloc. So, if you are just copying data after memory allocation, then malloc is the choice

Memory Leak:

When memory is created in heap, and we forget to delete it. 


void func() 
   char *ptr = (char *) malloc(5* sizeof(char)); 
  
   /* Do some work */
  
   return; /* Return without freeing ptr*/

Dangling Pointer:

Pointer pointing to non-existing location is called dangling pointer.
Pointer pointing to the memory address of any variable , freed and is still pointing to the same memory location

To ensure pointer is no longer dangling

#include<stdlib.h>
{
    char *ptr = malloc(Constant_Value);
    .......
    .......
    .......
    free (ptr);  /* ptr now becomes a dangling pointer */
    ptr = NULL   /* ptr is no more dangling pointer */
}

Dynamically allocate a 2-D array

Single Pointer: int *arr = (int *)malloc(r*c*sizeof(int));
*(arr + i*c +j) = value;

Arrays of Pointer: 
int *arr[r];
for (i = 0 ; i < r; i++)
     arr[i]  = (int *)malloc(c*sizeof(int));
arr[i][j] = value;

Double Pointer:

int **arr = (int **)malloc(r * sizeof(int *)); 
for (i=0; i<r; i++) 
         arr[i] = (int *)malloc(c * sizeof(int)); 
  arr[i][j] = value;

Comments

Popular posts from this blog

bb.utils.contains yocto

Difference between RDEPENDS and DEPENDS in Yocto

PR, PN and PV Variable in Yocto