0% found this document useful (0 votes)
322 views14 pages

Dynamic Memory Allocation in C using malloc(), calloc(), free() and realloc() - GeeksforGeeks

Uploaded by

kvns.19810808
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
322 views14 pages

Dynamic Memory Allocation in C using malloc(), calloc(), free() and realloc() - GeeksforGeeks

Uploaded by

kvns.19810808
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 14

12/13/24, 6:00 AM Dynamic Memory Allocation in C using malloc(), calloc(), free() and realloc() - GeeksforGeeks

Dynamic Memory Allocation in C using malloc(),


calloc(), free() and realloc()
Last Updated : 11 Oct, 2024

Since C is a structured language, it has some fixed rules for programming.


One of them includes changing the size of an array. An array is a
collection of items stored at contiguous memory locations.

As can be seen, the length (size) of the array above is 9. But what if there
is a requirement to change this length (size)? For example,

If there is a situation where only 5 elements are needed to be entered


in this array. In this case, the remaining 4 indices are just wasting
memory in this array. So there is a requirement to lessen the length
(size) of the array from 9 to 5.
Take another situation. In this, there is an array of 9 elements with all
9 indices filled. But there is a need to enter 3 more elements in this
array. In this case, 3 indices more are required. So the length (size) of
the array needs to be changed from 9 to 12.

This procedure is referred to as Dynamic Memory Allocation in C.

https://www.geeksforgeeks.org/dynamic-memory-allocation-in-c-using-malloc-calloc-free-and-realloc/ 1/20
12/13/24, 6:00 AM Dynamic Memory Allocation in C using malloc(), calloc(), free() and realloc() - GeeksforGeeks

Dynamic memory allocation using malloc(), calloc(), free(), and realloc() is


essential for efficient memory management in C. If you’re looking to
master these concepts and their application in data structures, the C
Programming Course Online with Data Structures provides an in-depth
understanding of memory allocation and management in C.

Therefore, 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. free()
4. realloc()

Let’s look at each of them in greater detail.

C malloc()
Courses @35% Off C method
C Basics C Data Types C Operators C Input and Output C Control Flow C Fun
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:

https://www.geeksforgeeks.org/dynamic-memory-allocation-in-c-using-malloc-calloc-free-and-realloc/ 2/20
12/13/24, 6:00 AM Dynamic Memory Allocation in C using malloc(), calloc(), free() and realloc() - GeeksforGeeks

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
4 int main()
5 {
6
7 // This pointer will hold the
8 // base address of the block created
9 int* ptr;
10 int n, i;
11
12 // Get the number of elements for the array
13 printf("Enter number of elements:");
14 scanf("%d",&n);
15 printf("Entered number of elements: %d\n", n);
16
17 // Dynamically allocate memory using malloc()

https://www.geeksforgeeks.org/dynamic-memory-allocation-in-c-using-malloc-calloc-free-and-realloc/ 3/20
12/13/24, 6:00 AM Dynamic Memory Allocation in C using malloc(), calloc(), free() and realloc() - GeeksforGeeks

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


19
20 // Check if the memory has been successfully
21 // allocated by malloc or not
22 if (ptr == NULL) {
23 printf("Memory not allocated.\n");
24 exit(0);
25 }
26 else {
27
28 // Memory has been successfully allocated
29 printf("Memory successfully allocated using
malloc.\n");
30
31 // Get the elements of the array
32 for (i = 0; i < n; ++i) {
33 ptr[i] = i + 1;
34 }
35
36 // Print the elements of the array
37 printf("The elements of the array are: ");
38 for (i = 0; i < n; ++i) {
39 printf("%d, ", ptr[i]);
40 }
41 }
42
43 return 0;
44 }

Output

Enter number of elements:7


Entered number of elements: 7
Memory successfully allocated using malloc.
The elements of the array are: 1, 2, 3, 4, 5, 6, 7,

C calloc() method

https://www.geeksforgeeks.org/dynamic-memory-allocation-in-c-using-malloc-calloc-free-and-realloc/ 4/20
12/13/24, 6:00 AM Dynamic Memory Allocation in C using malloc(), calloc(), free() and realloc() - GeeksforGeeks

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.

Example of calloc() in C

https://www.geeksforgeeks.org/dynamic-memory-allocation-in-c-using-malloc-calloc-free-and-realloc/ 5/20
12/13/24, 6:00 AM Dynamic Memory Allocation in C using malloc(), calloc(), free() and realloc() - GeeksforGeeks

1 #include <stdio.h>
2 #include <stdlib.h>
3
4 int main()
5 {
6
7 // This pointer will hold the
8 // base address of the block created
9 int* ptr;
10 int n, i;
11
12 // Get the number of elements for the array
13 n = 5;
14 printf("Enter number of elements: %d\n", n);
15
16 // Dynamically allocate memory using calloc()
17 ptr = (int*)calloc(n, sizeof(int));
18
19 // Check if the memory has been successfully
20 // allocated by calloc or not
21 if (ptr == NULL) {
22 printf("Memory not allocated.\n");
23 exit(0);
24 }
25 else {
26
27 // Memory has been successfully allocated
28 printf("Memory successfully allocated using
calloc.\n");
29
30 // Get the elements of the array
31 for (i = 0; i < n; ++i) {
32 ptr[i] = i + 1;
33 }
34
35 // Print the elements of the array
36 printf("The elements of the array are: ");
37 for (i = 0; i < n; ++i) {
38 printf("%d, ", ptr[i]);
39 }

https://www.geeksforgeeks.org/dynamic-memory-allocation-in-c-using-malloc-calloc-free-and-realloc/ 6/20
12/13/24, 6:00 AM Dynamic Memory Allocation in C using malloc(), calloc(), free() and realloc() - GeeksforGeeks

}
41
42 return 0;
43 }

Output

Enter number of elements: 5


Memory successfully allocated using calloc.
The elements of the array are: 1, 2, 3, 4, 5,

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
https://www.geeksforgeeks.org/dynamic-memory-allocation-in-c-using-malloc-calloc-free-and-realloc/ 7/20
12/13/24, 6:00 AM Dynamic Memory Allocation in C using malloc(), calloc(), free() and realloc() - GeeksforGeeks

1 #include <stdio.h>
2 #include <stdlib.h>
3
4 int main()
5 {
6
7 // This pointer will hold the
8 // base address of the block created
9 int *ptr, *ptr1;
10 int n, i;
11
12 // Get the number of elements for the array
13 n = 5;
14 printf("Enter number of elements: %d\n", n);
15
16 // Dynamically allocate memory using malloc()
17 ptr = (int*)malloc(n * sizeof(int));
18
19 // Dynamically allocate memory using calloc()
20 ptr1 = (int*)calloc(n, sizeof(int));
21
22 // Check if the memory has been successfully
23 // allocated by malloc or not
24 if (ptr == NULL || ptr1 == NULL) {
25 printf("Memory not allocated.\n");
26 exit(0);
27 }
28 else {
29
30 // Memory has been successfully allocated
31 printf("Memory successfully allocated using
malloc.\n");
32
33 // Free the memory
34 free(ptr);
35 printf("Malloc Memory successfully
freed.\n");
36

https://www.geeksforgeeks.org/dynamic-memory-allocation-in-c-using-malloc-calloc-free-and-realloc/ 8/20
12/13/24, 6:00 AM Dynamic Memory Allocation in C using malloc(), calloc(), free() and realloc() - GeeksforGeeks

// Memory has been successfully allocated


38 printf("\nMemory successfully allocated
using calloc.\n");
39
40 // Free the memory
41 free(ptr1);
42 printf("Calloc Memory successfully
freed.\n");
43 }
44
45 return 0;
46 }

Output

Enter number of elements: 5


Memory successfully allocated using malloc.
Malloc Memory successfully freed.

Memory successfully allocated using calloc.


Calloc Memory successfully freed.

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'.

https://www.geeksforgeeks.org/dynamic-memory-allocation-in-c-using-malloc-calloc-free-and-realloc/ 9/20
12/13/24, 6:00 AM Dynamic Memory Allocation in C using malloc(), calloc(), free() and realloc() - GeeksforGeeks

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

Example of realloc() in C

1 #include <stdio.h>
2 #include <stdlib.h>
3
4 int main()
5 {
6
7 // This pointer will hold the
8 // base address of the block created
9 int* ptr;
10 int n, i;
11
12 // Get the number of elements for the array
13 n = 5;
14 printf("Enter number of elements: %d\n", n);
15
16 // Dynamically allocate memory using calloc()
17 ptr = (int*)calloc(n, sizeof(int));
18
19 // Check if the memory has been successfully
20 // allocated by malloc or not

https://www.geeksforgeeks.org/dynamic-memory-allocation-in-c-using-malloc-calloc-free-and-realloc/ 10/20
12/13/24, 6:00 AM Dynamic Memory Allocation in C using malloc(), calloc(), free() and realloc() - GeeksforGeeks

if (ptr == NULL) {
22 printf("Memory not allocated.\n");
23 exit(0);
24 }
25 else {
26
27 // Memory has been successfully allocated
28 printf("Memory successfully allocated using
calloc.\n");
29
30 // Get the elements of the array
31 for (i = 0; i < n; ++i) {
32 ptr[i] = i + 1;
33 }
34
35 // Print the elements of the array
36 printf("The elements of the array are: ");
37 for (i = 0; i < n; ++i) {
38 printf("%d, ", ptr[i]);
39 }
40
41 // Get the new size for the array
42 n = 10;
43 printf("\n\nEnter the new size of the array:
%d\n", n);
44
45 // Dynamically re-allocate memory using
realloc()
46 ptr = (int*)realloc(ptr, n * sizeof(int));
47
48 if (ptr == NULL) {
49 printf("Reallocation Failed\n");
50 exit(0);
51 }
52
53 // Memory has been successfully allocated
54 printf("Memory successfully re-allocated
using realloc.\n");
55
56 // Get the new elements of the array
57 for (i = 5; i < n; ++i) {
58 ptr[i] = i + 1;
https://www.geeksforgeeks.org/dynamic-memory-allocation-in-c-using-malloc-calloc-free-and-realloc/ 11/20
12/13/24, 6:00 AM Dynamic Memory Allocation in C using malloc(), calloc(), free() and realloc() - GeeksforGeeks

}
60
61 // Print the elements of the array
62 printf("The elements of the array are: ");
63 for (i = 0; i < n; ++i) {
64 printf("%d, ", ptr[i]);
65 }
66
67 free(ptr);
68 }
69
70 return 0;
71 }

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,

One another example for realloc() method is:

1 #include <stdio.h>
2 #include <stdlib.h>
3 int main()
4 {
5 int index = 0, i = 0, n,
6 *marks; // this marks pointer hold the base addre
7 // of the block created
8 int ans;
9 marks = (int*)malloc(sizeof(
10 int)); // dynamically allocate memory using mallo

https://www.geeksforgeeks.org/dynamic-memory-allocation-in-c-using-malloc-calloc-free-and-realloc/ 12/20
12/13/24, 6:00 AM Dynamic Memory Allocation in C using malloc(), calloc(), free() and realloc() - GeeksforGeeks

// check if the memory is successfully allocated by


12 // malloc or not?
13 if (marks == NULL) {
14 printf("memory cannot be allocated");
15 }
16 else {
17 // memory has successfully allocated
18 printf("Memory has been successfully allocated by
19 "using malloc\n");
20 printf("\n marks = %pc\n",
21 marks); // print the base or beginning
22 // address of allocated memory
23 do {
24 printf("\n Enter Marks\n");
25 scanf("%d", &marks[index]); // Get the marks
26 printf("would you like to add more(1/0): ");
27 scanf("%d", &ans);
28
29 if (ans == 1) {
30 index++;
31 marks = (int*)realloc(
32 marks,
33 (index + 1)
34 * sizeof(
35 int)); // Dynamically realloc
36 // memory by using
realloc
37 // check if the memory is successfully
38 // allocated by realloc or not?
39 if (marks == NULL) {
40 printf("memory cannot be allocated");
41 }
42 else {
43 printf("Memory has been successfully
44 "reallocated using realloc:\n"
45 printf(
46 "\n base address of marks are:%pc
47 marks); ////print the base or
48 ///beginning address of
49 ///allocated memory
50 }

https://www.geeksforgeeks.org/dynamic-memory-allocation-in-c-using-malloc-calloc-free-and-realloc/ 13/20
12/13/24, 6:00 AM Dynamic Memory Allocation in C using malloc(), calloc(), free() and realloc() - GeeksforGeeks

}
52 } while (ans == 1);
53 // print the marks of the students
54 for (i = 0; i <= index; i++) {
55 printf("marks of students %d are: %d\n ", i,
56 marks[i]);
57 }
58 free(marks);
59 }
60 return 0;
61 }

Output

Subscribe for 1 Year and get 1 Extra year of access completely FREE!
Upgrade to GeeksforGeeks Premium today!

Choose GeeksforGeeks Premium and also get access to 50+ Courses with
Certifications, Unlimited Article Summarization, 100% Ad free
environment, A.I. Bot support in all coding problems, and much more. Go
Premium!

https://www.geeksforgeeks.org/dynamic-memory-allocation-in-c-using-malloc-calloc-free-and-realloc/ 14/20

You might also like