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

Dynamic Memory Allocation 19

1) Static memory allocation assigns memory to variables at compile time before program execution, while dynamic allocation assigns memory at runtime. 2) Static allocation uses the stack and is faster but less efficient, while dynamic uses the heap and is slower but more efficient by allowing memory reusability. 3) The key dynamic memory functions are malloc() to allocate, calloc() to allocate and initialize to zero, and free() to de-allocate memory when no longer needed.

Uploaded by

Jonathan
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
166 views

Dynamic Memory Allocation 19

1) Static memory allocation assigns memory to variables at compile time before program execution, while dynamic allocation assigns memory at runtime. 2) Static allocation uses the stack and is faster but less efficient, while dynamic uses the heap and is slower but more efficient by allowing memory reusability. 3) The key dynamic memory functions are malloc() to allocate, calloc() to allocate and initialize to zero, and free() to de-allocate memory when no longer needed.

Uploaded by

Jonathan
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 14

Difference between Static and Dynamic Memory Allocation in C

Memory Allocation: Memory allocation is a process by which computer programs and services are assigned
with physical or virtual memory space. The memory allocation is done either before or at the time of program
execution. There are two types of memory allocations:
1. Compile-time or Static Memory Allocation
2. Run-time or Dynamic Memory Allocation
Static Memory Allocation: Static Memory is allocated for declared variables by the compiler. The address can
be found using the address of operator and can be assigned to a pointer. The memory is allocated during
compile time.
Dynamic Memory Allocation: Memory allocation done at the time of execution(run time) is known
as dynamic memory allocation. Functions calloc() and malloc() support allocating dynamic memory. In the
Dynamic allocation of memory space is allocated by using these functions when the value is returned by
functions and assigned to pointer variables.
Difference Between Static and Dynamic Memory Allocation in C:

S.No Static Memory Allocation Dynamic Memory Allocation

In the static memory allocation, In the Dynamics memory allocation, variables

variables get allocated get allocated only if your program unit gets

1 permanently. active.

Static Memory Allocation is done Dynamics Memory Allocation is done during

2 before program execution. program execution.

It uses stack for managing the It uses heap for managing the dynamic

3 static allocation of memory allocation of memory

4 It is less efficient It is more efficient

In Dynamics Memory Allocation, there is

In Static Memory Allocation, memory re-usability and memory can be freed

5 there is no memory re-usability when not required

In static memory allocation, once

the memory is allocated, the In dynamic memory allocation, when memory is

6 memory size can not change. allocated the memory size can be changed.

1
This allows reusing the memory. The user can

In this memory allocation scheme, allocate more memory when required. Also, the

we cannot reuse the unused user can release the memory when the user

7 memory. needs it.

In this memory allocation scheme,

execution is faster than dynamic In this memory allocation scheme, execution is

8 memory allocation. slower than static memory allocation.

In this memory is allocated at

9 compile time. In this memory is allocated at run time.

In this allocated memory remains In this allocated memory can be released at any

10 from start to end of the program. time during the program.

Example: This static memory

allocation is generally used Example: This dynamic memory allocation is

11 for array. generally used for linked list.

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


2
Since C is a structured language, it has some fixed rules for programming. One of it includes changing the size
of an array. An array is collection of items stored at continuous memory locations.

As it can be seen that the length (size) of the array above made 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.

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()

3
1. C malloc() method

 “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 initializes each block with default garbage value.

Syntax:
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:
#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 malloc()


ptr = (int*)malloc(n * sizeof(int));
4
// 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 malloc.\n");

// Get the elements of the array


for (i = 0; i < n; ++i) {
ptr[i] = i + 1; // *(ptr+i) = > a[i]
}

// Print the elements of the array


printf("The elements of the array are: ");
for (i = 0; i < n; ++i) {
printf("%d, ", ptr[i]); //*(ptr+i)
}
}

return 0;
}
Output:
Enter number of elements: 5
Memory successfully allocated using malloc.
The elements of the array are: 1, 2, 3, 4, 5,

2. C calloc() method

 “calloc” or “contiguous allocation” method in C is used to dynamically allocate the specified


number of blocks of memory of the specified type.

 It initializes each block with a default value ‘0’.


Syntax:
ptr = (cast-type*)calloc(n, element-size);
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.

5
If space is insufficient, allocation fails and returns a NULL pointer.
Example:
#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;
}

6
// 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,

3. 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:
free(ptr);

7
Example:

#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);

8
}
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.

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

9
 re-allocation of memory maintains the already present value and new blocks will be initialized
with default garbage value.
Syntax:
ptr = realloc(ptr, newSize);

where ptr is reallocated with new size 'newSize'.

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


Example:
filter_none
edit
play_arrow
brightness_4
#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


10
// 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;
sum+=ptr[i];
}

// 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 = realloc(ptr, n * sizeof(int));

// 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,

11
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,
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self
Paced Course at a student-friendly price and become industry ready.

Summary

12
 int *a, *b;

 if ((a = (int *)calloc(N, sizeof(int))) == NULL) {
 printf("A memory allocation error occurred\n");
 exit(1);
 }
 if ((b = (int *)malloc(N*sizeof(int))) == NULL) {
 printf("A memory allocation error occurred\n");
 exit(1);
 }
 ...
 free(a);
 free(b);

 In the above example, both a and b can be used as an array as if int a[N], b[N]; had been
declared.
 With calloc and malloc, N can be a variable. With array declarations, N must be a constant.
 The use of sizeof() is recommended to ensure portability of the code to another platform.

The program below calculates the sum of an arithmetic sequence.

#include <stdio.h>
int main() {
int i, * ptr, sum = 0;
ptr = calloc(10, sizeof(int));
if (ptr == NULL) {
printf("Error! memory not allocated.");
exit(0);
}
printf("Building and calculating the sequence sum of the first 10 terms \ n ");
for (i = 0; i < 10; ++i) { * (ptr + i) = i;
sum += * (ptr + i); ptr+i
}
printf("Sum = %d", sum);
free(ptr);
return 0;
}

Result:

Building and calculating the sequence sum of the first 10 terms


Sum = 45

13
calloc vs. malloc: Key Differences
The calloc function is generally more suitable and efficient than that of the malloc function.
While both the functions are used to allocate memory space, calloc can allocate multiple blocks
at a single time. You don't have to request for a memory block every time. The calloc function is
used in complex data structures which require larger memory space.

The memory block allocated by a calloc function is always initialized to zero while in malloc it
always contains a garbage value.

14

You might also like