Vous êtes sur la page 1sur 7

DYNAMIC MEMORY ALLOCATION IN C

The process of allocating memory during program execution is called dynamic memory
allocation.

DYNAMIC MEMORY ALLOCATION FUNCTIONS IN C

Although, C language inherently does not have any technique to allocate memory
dynamically, there are 4 library functions under "stdlib.h" for dynamic memory allocation.

1. malloc()
2. calloc()
3. realloc()
4. free()

Function Description

malloc() allocates requested size of bytes and returns a void pointer pointing to the first
byte of the allocated space

calloc() allocates space for an array of elements, initialize them to zero and then return
a void pointer to the memory

Free releases previously allocated memory

Realloc modify the size of previously allocated space

Memory Allocation Process


Global variables, static variables and program instructions get their memory
in permanent storage area whereas local variables are stored in area called Stack. The
memory space between these two regions is known as Heap area. This region is used for
dynamic memory allocation during execution of the program. The size of heap keeps
changing.
Differences between Static Memory Allocation & Dynamic Memory
Allocation

STATIC MEMORY ALLOCATION DYNAMIC MEMORY ALLOCATION

Memory is allocated before the execution of Memory is allocated during the execution of
the program begins (During Compilation). the program.

Variables remain permanently allocated. Allocated only when program unit is active.

In this type of allocation Memory cannot be In this type of allocation Memory can be
resized after the initial allocation. dynamically expanded and shrunk as
necessary.

Implemented using stacks. Implemented using heap.

Faster execution than Dynamic. Slower execution than static.

It is less efficient than Dynamic allocation It is more efficient than Static allocation
strategy. strategy.

Implementation of this type of allocation is Implementation of this type of allocation is


simple. complicated.

Memory cannot be reuse when it is no Memory can be freed when it is no longer


longer needed. needed & reuse or reallocate during
execution.
Allocating a block of memory: malloc()
malloc() function is used for allocating block of memory at runtime. This function reserves
a block of memory of given size and returns a pointer of type void. This means that we can
assign it to any type of pointer using typecasting. If it fails to locate enough space it returns
a NULL pointer.

Synatax:

void *ptr;

ptr = (cast_type *) malloc (byte_size);

Here, ptr is pointer of cast-type. The malloc() function returns a pointer to an area of
memory with size of byte size.

Example

int *x;

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

free(x);

This statement will allocate 200 bytes and the pointer points to the address of first byte of
memory.

Example Program

Write a C program to find the sum of n elements using dynamic memory allocation
function malloc().

#include <stdio.h>
#include<conio.h>
#include <stdlib.h>
void main()
{
int num, i,num, *ptr, sum = 0;
clrscr();
printf("Enter number of elements: ");
scanf("%d", &num);
ptr = (int*) malloc(num * sizeof(int)); //memory allocated using malloc
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 = sum + (*(ptr + i));
}
printf("Sum = %d", sum);
free(ptr);
getch();
}

Allocating multiple blocks of memory: calloc()


The name calloc stands for "contiguous allocation".
calloc() allocates space for an array elements, initializes to zero and then returns a pointer
to memory
The only difference between malloc() and calloc() is that, malloc() allocates single block of
memory whereas calloc() allocates multiple blocks of memory each of same size and sets all
bytes to zero.
calloc function is normally used for allocating memory to derived data types such
as arrays and structures. If it fails to locate enough space it returns a NULL pointer.

Synatax:

void *ptr;

ptr = (cast_type *) calloc (n,size);

Example 1:-

int *x;

x = (int *) calloc (50,2); (or) x = (int *) calloc (50,sizeof(int));

free(x);
Example 2:-

struct employee

char *name[35];

int salary;

};

typedef struct employee emp;

emp *e1;

e1 = ( emp *) calloc(10, sizeof(emp));

Example Program

Write a C program to find the sum of n elements using dynamic memory allocation
function calloc().

#include <stdio.h>
#include<conio.h>
#include <stdlib.h>
void main()
{
int num, i,num, *ptr, sum = 0;
clrscr();
printf("Enter number of elements: ");
scanf("%d", &num);
ptr = (int*) calloc(num, sizeof(int)); //memory allocated using calloc()
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 = sum + (*(ptr + i));
}
printf("Sum = %d", sum);
free(ptr);
getch();
}

Altering the size of a block : realloc()


If the previously allocated memory is insufficient or more than required, you can change the
previously allocated memory size using realloc().

Syntax

int *x;

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

x = (int * ) realloc ( x,100 ); // allocated a new memory to variable x.

Example Program

#include <stdio.h>
#include <stdlib.h>
#include<conio.h>
void main()
{
char *str;
clrscr();

/* Initial memory allocation */


str = (char *) malloc(12);
strcpy(str, "KSRM College");
printf("String = %s, Address = %u\n", str, str);

/* Reallocating memory */
str = (char *) realloc(str, 30);
strcat(str, "of engineering");
printf("String = %s, Address = %u\n", str, str);
free(str);
getch();
}

Releasing the used space : free()


When you allocate memory with either malloc(), calloc() or realloc(), it is taken from the
dynamic memory pool that is available to your program. This pool is sometimes called
the heap, and it is finite. When your program finishes using a particular block of dynamically
allocated memory, you should deallocate, or free, the memory to make it available for
future use. To free memory that was allocated dynamically, use free().

Its prototype is
void free(void *ptr);

The free() function releases the memory pointed to by ptr. This memory must have been
allocated with malloc(), calloc(), or realloc(). If ptr is NULL, free() does nothing.

Example

int *x;

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

free(x);

Vous aimerez peut-être aussi