Dynamic Memory Allocation in C


Dynamic Memory Allocation in C



As you know, you have to declare the size of an array before you use it. Hence, the array you declared may be insufficient or more than required to hold data. To solve this issue, you can allocate memory dynamically.

Dynamic memory management refers to manual memory management. This allows you to obtain more memory when required and release it when not necessary.

There are four library functions defined under <stdlib.h> for dynamic memory allocation.


Dynamic Memory Allocation Functions

FunctionPurpose
malloc()Allocates the requested number of bytes and returns a pointer to the first byte of allocated space
calloc()Allocates space for an array of elements, initializes all bytes to zero, and returns a pointer to the memory
free()Deallocates the previously allocated memory
realloc()Changes the size of previously allocated memory

malloc()

The name malloc stands for memory allocation.

  • Allocates a single block of memory of the specified size

  • Returns a pointer of type void* (can be typecast to any pointer type)

  • Returns NULL if memory allocation fails

Syntax

ptr = (cast-type*) malloc(byte_size);

Example

ptr = (int*) malloc(100 * sizeof(int));

This statement allocates memory for 100 integers. Depending on the system, it allocates 200 bytes (2-byte int) or 400 bytes (4-byte int).


calloc()

The name calloc stands for contiguous allocation.

Difference between malloc() and calloc()

  • malloc() allocates a single block of memory

  • calloc() allocates multiple contiguous blocks and initializes all bytes to zero

Syntax

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

Example

ptr = (float*) calloc(25, sizeof(float));

This allocates contiguous memory for 25 float elements, each of size 4 bytes.


free()

Memory allocated using malloc() or calloc() does not get released automatically. You must explicitly free it.

Syntax

free(ptr);

This statement releases the memory pointed to by ptr.


realloc()

The realloc() function is used when the previously allocated memory is either insufficient or more than required.

Syntax

ptr = realloc(ptr, new_size);

This resizes the memory block pointed to by ptr to new_size.


Example 1: Using malloc() and free()

Program: Find the sum of n elements entered by the user using malloc().

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

int main()
{
int num, i, *ptr, sum = 0;

printf("Enter number of elements: ");
scanf("%d", &num);

ptr = (int*) malloc(num * sizeof(int));

if (ptr == NULL)
{
printf("Error! memory not allocated.");
exit(0);
}

printf("Enter elements of array: ");
for (i = 0; i < num; ++i)
{
scanf("%d", ptr + i);
sum += *(ptr + i);
}

printf("Sum = %d", sum);

free(ptr);
return 0;
}

Example 2: Using calloc() and free()

Program: Find the sum of n elements entered by the user using calloc().

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

int main()
{
int num, i, *ptr, sum = 0;

printf("Enter number of elements: ");
scanf("%d", &num);

ptr = (int*) calloc(num, sizeof(int));

if (ptr == NULL)
{
printf("Error! memory not allocated.");
exit(0);
}

printf("Enter elements of array: ");
for (i = 0; i < num; ++i)
{
scanf("%d", ptr + i);
sum += *(ptr + i);
}

printf("Sum = %d", sum);

free(ptr);
return 0;
}

Find Largest Element Using calloc()

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

int main()
{
int i, num;
float *data;

printf("Enter total number of elements (1 to 100): ");
scanf("%d", &num);

data = (float*) calloc(num, sizeof(float));

if (data == NULL)
{
printf("Error!!! memory not allocated.");
exit(0);
}

for (i = 0; i < num; ++i)
{
printf("Enter Number %d: ", i + 1);
scanf("%f", data + i);
}

for (i = 1; i < num; ++i)
{
if (*data < *(data + i))
*data = *(data + i);
}

printf("Largest element = %.2f", *data);
return 0;
}

Example 3: Using realloc()

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

int main()
{
int *ptr, i, n1, n2;

printf("Enter size of array: ");
scanf("%d", &n1);

ptr = (int*) malloc(n1 * sizeof(int));

printf("Address of previously allocated memory: ");
for (i = 0; i < n1; ++i)
printf("%u\t", ptr + i);

printf("\nEnter new size of array: ");
scanf("%d", &n2);

ptr = realloc(ptr, n2);

printf("Address of newly allocated memory: ");
for (i = 0; i < n2; ++i)
printf("%u\t", ptr + i);

return 0;
}

Programs to Try

  • Compile and run all example programs

  • Modify them to handle edge cases

  • Practice converting static arrays to dynamic arrays

Comments

Popular posts from this blog

Programming in C GXEST204 - KTU 2024 scheme syllabus notes pdf ------- Dr Binu V P

Structure of a C Program

Single and Multi Dimensional Arrays