L12.1-Dynamic Memory Allocation
L12.1-Dynamic Memory Allocation
1.
12/20/2024
Need of Dynamic Memory Allocation
We must know the exact size of memory required for static
memory allocation, since its allocated during the compilation
process. Dynamic memory allocation allocates memory at runtime,
hence its more flexible.
With Dynamic Memory Allocation in C, you can reallocate (extend
or shrink) memory at run time.
C programming language does not have its garbage collector (used
to clear unused memory automatically) or related concept.
Dynamic memory management allows to free/release unused
memory at runtime.
We can allocate and deallocate memory at runtime as per need.
Hence, we will always have exact amount of memory required.
With static memory allocation it is impossible to create memory for
big arrays. With dynamic memory allocation we can allocate as
much memory required for our program.
2.
12/20/2024
Functions for Dynamic Memory Allocation
Four Functions: malloc(), calloc(), realloc(), free().
1. malloc() function
malloc() allocates N bytes in memory and return pointer to
allocated memory.
The returned pointer contains link/handle to the allocated memory.
malloc() returns NULL pointer on failure.
Using that you can access the memory allocated.
Syntax:
void * malloc(number_of_bytes);
It returns void pointer (generic pointer). Which means we can
easily typecast it to any other pointer types.
It accepts an integer number_of_bytes, i.e. total bytes to allocate in
memory.
3.
12/20/2024
1. malloc() function
Example:
int N = 10; // Number of bytes to allocate
int *ptr; // Pointer variable to store address
ptr = (int *) malloc(N * sizeof(int));
// Allocate 10 * 4 bytes in memory
The above statement will allocate 10 * 4 bytes (if size of integer is
4 bytes).
ptr is a pointer to integer to store address of the allocated memory.
(int *) is typecast required. As, I mentioned above that malloc()
return void *. Hence, to work with void pointer we must typecast it
to suitable type.
N * sizeof(int) – Since size of int is not fixed on all compilers.
Hence, to get size of integer on current compiler I have used
sizeof() operator.
4.
12/20/2024
1. malloc() function
Example:
// Allocate memory for N integers
int N = 10;
int *ptr;
ptr = (int *) malloc (N * sizeof(int));
5.
12/20/2024
1. malloc() function
Example:
/**
* C program to demonstrate malloc() and free() function.
*/
#include <stdio.h>
#include <stdlib.h>
int main()
{
int i, max;
int *ptr;
6.
12/20/2024
1. malloc() function
// Allocate memory for 'max' integer elements
ptr = (int *) malloc(max * sizeof(int));
// If memory not allocated
if(ptr == NULL)
{
printf("Memory is not created!!!");
exit(0); // Exit from the program
}
// Input elements from user
printf("Enter %d elements: \n", max);
for (i = 0; i < max; i++)
scanf("%d", (ptr + i));
// Print all elements
printf("\nArray elements are:\n");
for (i = 0; i < max; i++)
printf("%d ", *(ptr + i));
// Release allocated memory 7.
12/20/2024
1. malloc() function
OUTPUT
Enter total number of elements: 5
Enter 5 elements:
10 20 30 40 50
8.
12/20/2024
2. calloc() function
calloc() function allocates memory contiguously. It allocates
multiple memory blocks and initializes all blocks with 0 (NULL).
Note: malloc() allocates uninitialized memory blocks.
Syntax:
void* calloc(number_of_blocks, number_of_bytes);
Similar to malloc() it returns void pointer.
It accepts two parameters number_of_blocks i.e. total blocks to
allocate and number_of_bytes i.e. bytes to allocate per block.
Therefore, you can say that calloc() will allocate total
(number_of_blocks * number_of_bytes) bytes. Each block
initialized with 0 (NULL).
9.
12/20/2024
2. calloc() function
Example:
int *ptr;
ptr = (int *) calloc(N, sizeof(int));
Here, all memory blocks are initialized with 0.
10.
12/20/2024
2. calloc() function
Example:
/**
* C program to demonstrate calloc() and free() function.
*/
#include <stdio.h>
#include <stdlib.h>
int main()
{
int i, max;
int *ptr;
11.
12/20/2024
2. calloc() function
Example:
// Allocate memory for 'max' integer elements
ptr = (int *) calloc(max, sizeof(int));
// If memory not allocated
if(ptr == NULL)
{
printf("Memory is not created!!!");
exit(0); // Exit from the program
}
// Input elements from user
printf("Enter %d elements: \n", max);
for (i = 0; i < max; i++)
scanf("%d", (ptr + i));
12.
12/20/2024
2. calloc() function
Example:
// Print all elements
printf("\nArray elements are:\n");
for (i = 0; i < max; i++)
printf("%d ", *(ptr + i));
// Release allocated memory
free(ptr);
return 0;
}
Output:
Enter total number of elements: 5
Enter 5 elements:
10 20 30 40 50
Array elements are:
10 20 30 40 50 13.
12/20/2024
3. realloc() function
When working with huge data and if the allocated memory is not
sufficient to store data. In that case, we need to alter/update the size
of an existing allocated memory blocks (which has been created by
either malloc() or calloc()).
We use realloc() function to alter/update the size of exiting
allocated memory blocks. The function may resize or move the
allocated memory blocks to a new location.
Syntax:
void* realloc(ptr, updated_memory_size);
Similar to all other functions for Dynamic Memory Allocation in C,
it returns void pointer. Which points to the address of existing or
newly allocated memory.
ptr is a pointer to memory block of previously allocated memory.
updated_memory_size is new (existing + new) size of the memory
block.
14.
12/20/2024
3. realloc() function
realloc() function may or may not allocate new memory blocks at
the same location.
The function will move data from old location to new location, if
memory allocated at new location. Hence, it ensure no data loss.
realloc() return NULL pointer on failure and releases original
memory blocks.
15.
12/20/2024
3. realloc() function
Example:
// Original memory blocks allocation
int N = 10;
int *ptr;
ptr = (int *) malloc(N * sizeof(int));
16.
12/20/2024
3. realloc() function
Example:
/**
* C program to demonstrate ralloc() and free() function.
*/
#include <stdio.h>
#include <stdlib.h>
int main()
{
int i, max, newSize;
int *ptr;
17.
12/20/2024
3. realloc() function
// Allocate memory for 'max' integer elements using calloc
ptr = (int *) calloc(max, sizeof(int));
// If memory not allocated
if(ptr == NULL)
{
printf("Memory is not created!!!");
exit(0); // Exit from the program
}
// Input elements from user
printf("Enter %d elements: \n", max);
for (i = 0; i < max; i++)
scanf("%d", (ptr + i));
18.
12/20/2024
3. realloc() function
// Reallocate memory
printf("\nEnter new size of the array: ");
scanf("%d", &newSize);
ptr = (int *) realloc(ptr, (newSize * sizeof(int)));
// Input elements in newly allocated memory
printf("\nEnter %d elements: \n", (newSize - max));
for (i = max; i < newSize; i++)
scanf("%d", (ptr + i));
// Print all elements
printf("\nArray elements are:\n");
for (i = 0; i < newSize; i++)
printf("%d ", *(ptr + i));
// Release allocated memory
free(ptr); 19.
12/20/2024
3. realloc() function
Output:
Enter total number of elements: 5
Enter 5 elements:
10 20 30 40 50
Enter 2 elements: 60 70
20.
12/20/2024
4. free() function
C programming has a built-in library function free() to clear or
release the unused memory.
The free() function clears the pointer (assigns NULL to the pointer)
to clear the dynamically allocated memory. If pointer contains
NULL, then free() does nothing (because pointer will not be
pointing at any memory addresses). If it contains any address of
dynamically allocated memory, free() will clear pointer by
assigning NULL.
Syntax
free(ptr);
Example
int N = 10;
int *ptr;
// Allocate memory using malloc
ptr = (int *) malloc(N * sizeof(int));
// Free allocated memory
free(ptr); 21.
12/20/2024
References
Yashwant Kanetkar, Let us C”, BPB Publications.
B. Kernighan and D. Ritchie, The ANSI C Programming Language,
PHI.
E. Balagurusamy, “Programming in ANSI C”, TMH.
Kernighan and Dennis M. Ritchie, The C Programming Language,
Pearson Education.
https://codeforwin.org/2017/10/pointers-in-c-declare-initialize-and-
use.html
22.
12/20/2024