Dynamic Memory allocation in C

There are 2 types of  Memory allocation: 1. Static memory allocation, 2. Dynamic memory allocation.
The concept of Dynamic memory allocation in C language enables the C programmer to allocate memory at runtime.
Possible by 4 function of stdlib.h header file.
1. malloc() : allocates single block of requested memory
2. calloc() : allocates multiple block of requested memory
3. realloc() : reallocates the memory occupied by malloc() or calloc() functions
4. free() : frees the dynamically allocated memory.


Malloc()

  • Malloc stands for memory allocation.
  • Mainly used to allocate memory to a pointer variable or for a structure also during execution time.
  • Allocates required size in terms of bytes and return pointer to the starting address of memory block.
  • Used to dynamically allocate a large single block of memory with specified size.
  • Defined in <stdlib.h> C header file.
  • Malloc() uses sizeof() function to define its size. sizeof() is a predefined C function that returns the size of variable. 
  • example: int a;
  •                printf(sizeof(a));

  • Syntax :  Datatype ptr = (cast_type*) malloc (size_type);
                eg  :  ptr = (int*) malloc (50*sizeof(int));
        which means integer memory space is 4. which gives 50*4=200 bytes.

  • Malloc() will return NULL in 2 cases:
  1.  1. memory space is insufficient  
  2.  2. malloc() fails to assign memory 
  • Example:





Online C Compiler IDE

malloc program to print n number of elements


Calloc()

  • The calloc() stands for contiguous memory allocation.
  • This function allocates multiple block of requested memory.
  • It initially initialize all bytes to zero. 
  • It returns NULL if memory is not sufficient. 
  • It allocates multiple block of memory.
  • Defined in <stdlib.h>
  • Syntax :  Datatype ptr = (cast_type*) calloc (n,size_type);
                eg  :  ptr = (float*) calloc (25,sizeof(float));
  • Example:


Online C Compiler IDE

calloc program to print n number of elements


Realloc()

  • The realloc function refers to reallocation of dynamic memory, whenever we allocate the memory with the help of malloc or calloc.
  • If the allocated memory is insufficient or more, we need to use realloc to reallocate the memory.
  • Once we reallocate the memory, it resize the existing as per the requirement.
  • Syntax :  Datatype ptr = realloc(ptr,newsize);
  •                 eg  :  ptr = realloc(ptr , 10*sizeof(int));
  • Example:



Online C Compiler IDE

Realloc example

Free()

  • The memory occupied by malloc() or calloc() functions must be released by calling free() function. Otherwise, it will consume memory until program exit. 
  • Syntax :  free(ptr);
  • Example:

Online C Compiler IDE

 Pointers 

The pointer in C language is a variable which stores the address of another variable. This variable can be of type int, char, array, function, or any other pointer. The size of the pointer depends on the architecture. However, in 32 bit architecture the size of a pointer is 2 byte.
Example:
1. int n = 10; 
2. int* p = &n; // Variable p of type pointer is pointing to the address of the variable n of type integer.


  Declaring a pointer 
 The pointer in c language can be declared using * (asterisk symbol). It is also known as indirection pointer used to dereference a pointer.
 1. int *a;//pointer to int 
2 . char *c;//pointer to char  


NULL Pointer 
 A pointer that is not assigned any value but NULL is known as the NULL pointer. If you don't have any address to be specified in the pointer at the time of declaration, you can assign NULL value. It will provide a better approach. 


Dangling Pointers

A pointer pointing to a memory location that has been deleted (or freed) is called a dangling pointer. Such a situation can lead to unexpected behavior in the program and also serve as a source of bugs in C programs.


There are three different ways where a pointer acts as a dangling pointer:


1. De-allocation of Memory
When a memory pointed by a pointer is deallocated the pointer becomes a dangling pointer.


2. Function Call 
When the local variable is not static and the function returns a pointer to that local variable. The pointer pointing to the local variable becomes dangling pointer.


3. Variable Goes Out of Scope
When a variable goes out of scope the pointer pointing to that variable becomes a dangling pointer.


-----------------------------------------------------------------------------------------------------------------------------

Questions:

1.Explain the differences between malloc and calloc, functions in C programming.

malloc:
malloc() is used to indicate memory allocation
malloc() only takes one argument
malloc() is faster than calloc().
malloc() has high time efficiency
does not initialize the memory to zero

Calloc:
calloc() is used to indicate contiguous memory allocation
calloc() takes two arguments.
calloc() is slower than malloc()
calloc() has low time efficiency
 initializes the memory to zero

2.Discuss the concept of an array of pointers in C programming.

In C, an array of pointer is essentially an array where each element is a pointer. These pointers can point to different data types or memory locations, providing flexibility and dynamic memory allocation.

Declaring an Array of Pointers:

To declare an array of pointers in C, you specify the base type followed by an asterisk (*) to indicate that it's a pointer, and then use square brackets [] to denote the array size.

Initializing an Array of Pointers:

There are different ways to initialize an array of pointers. You can initialize each pointer individually or assign the pointers to the addresses of existing variables or dynamically allocate memory using functions like malloc()

Accessing Elements of an Array of Pointers:

Once an array of pointers is initialized, you can access the elements by using array indexing and dereferencing the pointers.

Example:

#include <stdio.h> int main() { // Array of pointers to strings char *names[3] = {"Hello", "World", "C"}; // Accessing and printing strings using array of pointers for (int i = 0; i < 3; i++) { printf("Name %d: %s\n", i + 1, names[i]); } return 0; }


3.Define what a dangling pointer is in the context of C programming. or
What are the situations where a pointer becomes dangling pointer?

A pointer pointing to a memory location that has been deleted (or freed) is called a dangling pointer. Such a situation can lead to unexpected behavior in the program and also serve as a source of bugs in C programs.

There are three different ways where a pointer acts as a dangling pointer:
1. De-allocation of Memory
When a memory pointed by a pointer is deallocated the pointer becomes a dangling pointer.

2. Function Call 
When the local variable is not static and the function returns a pointer to that local variable. The pointer pointing to the local variable becomes dangling pointer.

3. Variable Goes Out of Scope
When a variable goes out of scope the pointer pointing to that variable becomes a dangling pointer.

4. Explain realloc and free function with example.

realloc

  • The realloc function refers to reallocation of dynamic memory, whenever we allocate the memory with the help of malloc or calloc.
  • If the allocated memory is insufficient or more, we need to use realloc to reallocate the memory.
  • Once we reallocate the memory, it resize the existing as per the requirement.
  • Syntax :  Datatype ptr = realloc(ptr,newsize);
  •                 eg  :  ptr = realloc(ptr , 10*sizeof(int));
  • Example:

#include <stdio.h> 
#include <stdlib.h> 
int main() 
int* ptr; 
int n, i; 
n = 5; 
printf("Enter number of elements: %d\n", n); 
ptr = (int*)calloc(n, sizeof(int)); 
    if (ptr == NULL) { 
        printf("Memory not allocated.\n"); 
        exit(0); 
    } 
    else { 
        printf("Memory successfully allocated using calloc.\n"); 
        for (i = 0; i < n; ++i) { 
            ptr[i] = i + 1; 
        } 
        printf("The elements of the array are: "); 
        for (i = 0; i < n; ++i) { 
            printf("%d, ", ptr[i]); 
        } 
        n = 10; 
        printf("\n\nEnter the new size of the array: %d\n", n); 
        ptr = (int*)realloc(ptr, n * sizeof(int)); 
        printf("Memory successfully re-allocated using realloc.\n"); 
        for (i = 5; i < n; ++i) { 
            ptr[i] = i + 1; 
        } 
        printf("The elements of the array are: "); 
        for (i = 0; i < n; ++i) { 
            printf("%d, ", ptr[i]); 
        } 
        free(ptr); 
    } 
return 0; 

Free()

  • The memory occupied by malloc() or calloc() functions must be released by calling free() function. Otherwise, it will consume memory until program exit. 
  • Syntax :  free(ptr);
  • Example:
#include<stdio.h>
#include<stdlib.h>
int main()
{
int* ptr;
int n,i;
printf("enter the no. of elements: ");
scanf("%d",&n);
ptr=(int*)malloc(n*sizeof(int));
for(i=0;i<n;i++)
{
ptr[i]= i+1;
}
printf("the elements of array are: ");
for(i=0;i<n;i++)
{
printf("%d",ptr[i]);
}
free(ptr);
}


 5.What is dynamic memory allocation? 

The memory space occupied by variable and arrays in a system memory remains fixed during a program execution. Even if the allocated space at compile time proves insufficient. The concept of dynamic memory allocation in c was introduced  to address this issue. This allows for allocation and de-allocation of memory during runtime in c.

Possible by 4 function of stdlib.h header file.
1. malloc() : allocates single block of requested memory
2. calloc() : allocates multiple block of requested memory
3. realloc() : reallocates the memory occupied by malloc() or calloc() functions
4. free() : frees the dynamically allocated memory.

6. What is the use of pointer variables in C?

There are many applications of pointers in c language:

1) Dynamic memory allocation In c language, we can dynamically allocate memory using malloc() and calloc() functions where the pointer is used. 

 2) Arrays, Functions, and Structures Pointers in c language are widely used in arrays, functions, and structures. It reduces the code and improves the performance. 

7. Write a C program to find a maximum and minimum number in an array using dynamic memory allocation.

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

int main() {
    int *arr, n, i, min, max;

    printf("Enter the number of elements in the array: ");
    scanf("%d", &n);

    arr = (int*)malloc(n * sizeof(int));
    if (arr == NULL) {
        printf("Memory allocation failed!\n");
        return 1;
    }

    printf("Enter the elements of the array:\n");
    for (i = 0; i < n; i++) {
        scanf("%d", &arr[i]);
    }

    min = arr[0];
    max = arr[0];

    for (i = 1; i < n; i++) {
        if (arr[i] < min) {
            min = arr[i];
        }
        if (arr[i] > max) {
            max = arr[i];
        }
    }

    printf("Minimum number: %d\n", min);
    printf("Maximum number: %d\n", max);

    free(arr);
    return 0;
}


Popular Posts