0% found this document useful (0 votes)
9 views

Dynamic Memory Allocation in C

The document explains dynamic memory allocation in C, highlighting four key functions: malloc(), calloc(), realloc(), and free(). It details how each function operates, including their syntax and examples, while contrasting dynamic memory allocation with static memory allocation. The document emphasizes the importance of freeing allocated memory to prevent wastage.

Uploaded by

dsairahulcsd
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

Dynamic Memory Allocation in C

The document explains dynamic memory allocation in C, highlighting four key functions: malloc(), calloc(), realloc(), and free(). It details how each function operates, including their syntax and examples, while contrasting dynamic memory allocation with static memory allocation. The document emphasizes the importance of freeing allocated memory to prevent wastage.

Uploaded by

dsairahulcsd
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 11

Dynamic memory allocation in C

Dynamic Memory Allocation can be defined as a procedure in


which the size of a data structure (like Array) is changed during the
runtime.
C provides some functions to achieve these tasks. There are 4 library
functions provided by C defined under <stdlib.h> header file to
facilitate dynamic memory allocation in C programming. They are:
1. malloc ( )
2. calloc ( )
3. realloc ( )
4. free ( )
static memory allocation dynamic memory allocation

memory is allocated at compile time. memory is allocated at run time.

memory can't be increased while executing program. memory can be increased while executing program.

used in array. used in linked list.

Before learning above functions, let's understand the difference between static memory allocation
Methods used for dynamic memory allocation.
malloc() allocates single block of requested memory.

calloc() allocates multiple block of requested memory.

reallocates the memory occupied by malloc() or calloc(


realloc()
functions.

free() frees the dynamically allocated memory.


C malloc() method
The “malloc” or “memory allocation” method in C is used to dynamically allocate a single large
block of memory with the specified size. It returns a pointer of type void which can be cast into a
pointer of any form. It doesn’t Initialize memory at execution time so that it has initialized each block
with the default garbage value initially.

Syntax of malloc() in C

ptr = (cast-type*) malloc(byte-size)

For Example:

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

Since the size of int is 4 bytes, this statement will allocate 400 bytes of memory.
And, the pointer ptr holds the address of the first byte in the allocated memory.

If space is insufficient, allocation fails and returns a NULL pointer.

Example of malloc() in C

1. #include<stdio.h>

2. #include<stdlib.h>

3. int main(){

4. int n,i,*ptr,sum=0;

5. printf("Enter number of elements: ");

6. scanf("%d",&n);
7. ptr=(int*)malloc(n*sizeof(int)); //memory allocated using malloc

8. if(ptr==NULL)

9. {

10. printf("Sorry! unable to allocate memory");

11. exit(0);

12. }

13. printf("Enter elements of array: ");

14. for(i=0;i<n;++i)

15. {

16. scanf("%d",ptr+i);

17. sum+=*(ptr+i);

18. }

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

20. free(ptr);

21. return 0;

22. }

OUTPUT
Enter number of elements: 3

Enter elements of array: 10

20

30

Sum=60

C calloc() method
1. “calloc” or “contiguous allocation” method in C is used to dynamically
allocate the specified number of blocks of memory of the specified type. it
is very much similar to malloc() but has two different points and these are:
2. It initializes each block with a default value ‘0’.
3. It has two parameters or arguments as compare to malloc().
Syntax of calloc() in C
ptr = (cast-type*)calloc(n, element-size);
here, n is the no. of elements and element-size is the size
of each element.
For Example:
ptr = (float*) calloc(25, sizeof(float));

This statement allocates contiguous space in memory for 25 elements each


with the size of the float.

If space is insufficient, allocation fails and returns a NULL pointer.

#include <stdio.h>

#include <stdlib.h>

int main()

// This pointer will hold the

// base address of the block created

int* ptr;

int n, i;

// Get the number of elements for the array

n = 5;

printf("Enter number of elements: %d\n", n);

// Dynamically allocate memory using calloc()

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


// Check if the memory has been successfully

// allocated by calloc or not

if (ptr == NULL) {

printf("Memory not allocated.\n");

exit(0);

else {

// Memory has been successfully allocated

printf("Memory successfully allocated using calloc.\n");

// Get the elements of the array

for (i = 0; i < n; ++i) {

ptr[i] = i + 1;

// Print the elements of the array

printf("The elements of the array are: ");

for (i = 0; i < n; ++i) {

printf("%d, ", ptr[i]);

return 0;

OUTPUT
Enter number of elements: 5

Memory successfully allocated using calloc.

The elements of the array are: 1, 2, 3, 4, 5,

C realloc() method
“realloc” or “re-allocation” method in C is used to dynamically change the memory allocation of a
previously allocated memory. In other words, if the memory previously allocated with the help of
malloc or calloc is insufficient, realloc can be used to dynamically re-allocate memory. re-allocation
of memory maintains the already present value and new blocks will be initialized with the default
garbage value.

Syntax of realloc() in C
ptr = realloc(ptr, newSize);
where ptr is reallocated with new size 'newSize'.

Example of realloc() in C

#include <stdio.h>

#include <stdlib.h>

int main()

// This pointer will hold the

// base address of the block created

int* ptr;

int n, i;

// Get the number of elements for the array

n = 5;

printf("Enter number of elements: %d\n", n);

// Dynamically allocate memory using calloc()

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


// Check if the memory has been successfully

// allocated by malloc or not

if (ptr == NULL) {

printf("Memory not allocated.\n");

exit(0);

else {

// Memory has been successfully allocated

printf("Memory successfully allocated using calloc.\n");

// Get the elements of the array

for (i = 0; i < n; ++i) {

ptr[i] = i + 1;

// Print the elements of the array

printf("The elements of the array are: ");

for (i = 0; i < n; ++i) {

printf("%d, ", ptr[i]);

// Get the new size for the array

n = 10;

printf("\n\nEnter the new size of the array: %d\n", n);

// Dynamically re-allocate memory using realloc()

ptr = (int*)realloc(ptr, n * sizeof(int));

if (ptr == NULL) {

printf("Reallocation Failed\n");

exit(0);

// Memory has been successfully allocated

printf("Memory successfully re-allocated using realloc.\n");

// Get the new elements of the array

for (i = 5; i < n; ++i) {

ptr[i] = i + 1;
}

// Print the elements of the array

printf("The elements of the array are: ");

for (i = 0; i < n; ++i) {

printf("%d, ", ptr[i]);

free(ptr);

return 0;

OUTPUT
Enter number of elements: 5

Memory successfully allocated using calloc.

The elements of the array are: 1, 2, 3, 4, 5,

Enter the new size of the array: 10

Memory successfully re-allocated using realloc.

The elements of the array are: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,

C free() method
“free” method in C is used to dynamically de-allocate the memory. The memory allocated using
functions malloc() and calloc() is not de-allocated on their own. Hence the free() method is used,
whenever the dynamic memory allocation takes place. It helps to reduce wastage of memory by
freeing it.

Syntax of free() in C

free(ptr);
Example of free() in C
#include <stdio.h>
#include <stdlib.h>
int main()
{
// This pointer will hold the
// base address of the block created
int *ptr, *ptr1;
int n, i;

// Get the number of elements for the array


n = 5;
printf("Enter number of elements: %d\n", n);

// Dynamically allocate memory using malloc()


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

// Dynamically allocate memory using calloc()


ptr1 = (int*)calloc(n, sizeof(int));
// Check if the memory has been successfully
// allocated by malloc or not
if (ptr == NULL || ptr1 == NULL) {
printf("Memory not allocated.\n");
exit(0);
}
else {

// Memory has been successfully allocated


printf("Memory successfully allocated using malloc.\n");

// Free the memory


free(ptr);
printf("Malloc Memory successfully freed.\n");

// Memory has been successfully allocated


printf("\nMemory successfully allocated using calloc.\n");

// Free the memory


free(ptr1);
printf("Calloc Memory successfully freed.\n");
}

return 0;
}
OUTPUT
Enter number of elements: 5
Memory successfully allocated using malloc.
Malloc Memory successfully freed.
Memory successfully allocated using calloc.
Calloc Memory successfully freed.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy