Dynamic Memory Allocation
Dynamic memory allocation is used to obtain and release
memoryduring program execution. Up until this point we
reserved memory at compile time using declarations.
wehaveto becarefulwith dynamic memoryallocation. It
operates at alow-level, you will often find yourself having to do a
certain amount of work to manage the memory it gives you.
For DMA, we must include the stdlib.h header file.
Prepared by : Er. Rhishav
Poudyal
Dymanic Memoryallocation
1
⚫ Dynamic memory management refers to manual memory
management. This allows you to obtain more memory when required
and releaseit when not necessary
.
⚫ Although C inherently does not have any technique to allocate
memory dynamically, there are 4 library functions defined under
<stdlib.h> for dynamic memory allocation.
Prepared by : Er. Rhishav
Poudyal
Dymanic Memoryallocation
2
Function
⚫ malloc()
⚫ calloc()
⚫ free()
⚫ realloc()
Use of Function
Allocatesrequested size of bytes and
returns apointer first byte of allocated
space
Allocatesspace for an arrayelements,
initializes to zero and then returns a pointer to
memory
deallocate the previouslyallocated space
Change the size of previouslyallocated space
Dymanic Memoryallocation
3
malloc()
The name malloc stands for "memory allocation".
The function malloc() reserves a block of memory of
specified size and return a pointer of type void which can be
casted into pointer of any form.
Syntax of malloc()
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.
If the space is insufficient, allocation fails and returns NULL
pointer.
ptr = (int*) malloc(100 * sizeof(int));
This statement will allocate either 200 or 400 according to
size of int 2 or 4 bytes respectively and the pointer points to
the address of first byte of memory.
Prepared by : Er. Rhishav
Poudyal
Dymanic Memoryallocation
malloc() example
To allocate space for 100 integers:
Prepared by : Er. Rhishav
Poudyal
Dymanic Memoryallocation
int *ip;
if ((ip = (int*)malloc(100 *
sizeof(int))) == NULL){
printf("out of memoryn");
exit();
}
⚫ Note we cast the return value to int*.
⚫ Note we also check if the function returns NULL.
Allocating memory for a struct
W
e can alsoallocate memory for astruct.
Example:
struct node *newPtr;
newPtr = (struct node *)malloc(sizeof(struct
node));
Memory allocated with malloc() lastsaslong aswe want it to.
It does not automaticallydisappearwhen afunction returns, asautomatic-
duration variablesdo, but it does not haveto remain for the entire
duration ofyour program, either.There isamechanismto free allocated
memory.
Prepared by : Er. Rhishav
Poudyal
Dymanic Memoryallocation
free()
Torelease allocated memory use
free()
⚫ Deallocatesmemory allocated bymalloc().
⚫ T
akesapointer asan argument.
e.g.
free(newPtr);
Freeingunused memory is agood idea,but it's not mandatory.When
your program exits,anymemory which it hasallocatedbut not
freed will be automaticallyreleased.
Prepared by : Er. Rhishav
Poudyal
Dymanic Memoryallocation
free()
⚫Dynamically allocated memory created with either calloc() or
malloc() doesn't get freed on its own. we must explicitly use
free() to release the space.
syntax of free()
free(ptr);
⚫This statement frees the space allocated in the memory pointed
byptr.
Prepared by : Er. Rhishav
Poudyal
Dymanic Memoryallocation
calloc()
⚫ The name calloc stands for "contiguous allocation".
⚫ 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.
Syntax of calloc()
⚫ ptr = (cast-type*)calloc(n, element-size);
⚫Thisstatement will allocate contiguous space in memory for an array of n elements.
Forexample:
ptr = (float*) calloc(25, sizeof(float));
Thisstatement allocates contiguous space in memory for an array of 25 elements each
of size of float, i.e, 4 bytes.
Prepared by : Er. Rhishav
Poudyal
Dymanic Memoryallocation
calloc() example
/* Using calloc() to initialize 100 floats to 0.0 */
#include <stdlib.h>
#include <stdio.h>
#define BUFFER_SIZE 100
int main(){
float * buffer;
int i;
if ((buffer = (float*)calloc(BUFFER_SIZE, sizeof(float))) == NULL){
printf("out of memoryn");
exit(1);
}
for (i=0; i < BUFFER_SIZE; i++)
printf(“buffer[%d] = %fn”, i, buffer[i]);
return 0;
}
Prepared by : Er. Rhishav
Poudyal
Dymanic Memoryallocation
realloc()
⚫If the previously allocated memory is insufficient or more than
required, we can change the previously allocated memory size
usingrealloc().
Syntax of realloc()
ptr = realloc(ptr, newsize);
Here, ptr is reallocated with size of newsize.
Prepared by : Er. Rhishav
Poudyal
Dymanic Memoryallocation
realloc()
Ifyou find you did not allocate enoughspace use realloc().
Y
ougive realloc() apointer (such asyou received from aninitial call
to malloc()) andanewsize,andrealloc doeswhatit canto give
you ablock of memory bigenoughto hold the new size.
int *ip;
ip = (int*)malloc(100 * sizeof(int));
...
/* need twice as much space */
ip = (int*)realloc(ip, 200 *
sizeof(int));
Prepared by : Er. Rhishav
Poudyal
Dymanic Memoryallocation
#include <stdio.h>
#include <stdlib.h>
int main()
{
int *ptr, i , n1, n2;
printf("Enter size of array:");
scanf("%d", &n1);
ptr = (int*) malloc(n1 *
sizeof(int));
printf("Addressof previously
allocated memory: ");
for(i = 0; i < n1; ++i)
printf("%ut",ptr + i);
Prepared by : Er. Rhishav
Poudyal
Dymanic Memoryallocation
printf(" nEnter new size of array:
");
scanf("%d", &n2);
ptr = realloc(ptr, n2);
for(i = 0; i < n2; ++i)
printf("%u t", ptr + i);
return 0;
}
printf("Error! memory not
allocated.");
exit(0);
Prepared by : Er. Rhishav
Poudyal
Dymanic Memoryallocation
#include <stdio.h> }
#include <stdlib.h> printf("Enter elements of array: ");
for(i = 0; i < num; ++i)
int main() {
{ scanf("%d", ptr + i);
int num, i, *ptr, sum = 0; sum += *(ptr + i);
printf("Enter number of elements: "); }
scanf("%d", &num); printf("Sum = %d", sum);
ptr = (int*) malloc(num *sizeof(int)); free(ptr);
if(ptr == NULL) return 0;
{ }
Memory Allocation - calloc()
Prepared by : Er. Rhishav
Poudyal
Dymanic Memoryallocation
Dymanic Memoryallocation
15
#include <stdio.h>
#include <stdlib.h>
int main()
{
int i, num;
float *data;
printf("Enter total number of
elements(1 to 100): ");
scanf("%d", &num);
data = (float*) calloc(num,
sizeof(float));
if(data == NULL)
{
printf("Error!!! memory not
allocated.");
Exit(0);
}
printf("n");
for(i = 0; i < num; ++i)
{
printf("Enter Number %d:", i +
1);
scanf("%f", data + i);
}
for(i = 1; i < num; ++i)
{
if(*data < *(data + i))
*data = *(data + i);
}
printf("Largest element = %.2f",
*data);
return 0;
}
Prepared by : Er. Rhishav Poudyal Dymanic Memoryallocation

Dynamic Memory Allocation in C programming

  • 1.
    Dynamic Memory Allocation Dynamicmemory allocation is used to obtain and release memoryduring program execution. Up until this point we reserved memory at compile time using declarations. wehaveto becarefulwith dynamic memoryallocation. It operates at alow-level, you will often find yourself having to do a certain amount of work to manage the memory it gives you. For DMA, we must include the stdlib.h header file. Prepared by : Er. Rhishav Poudyal Dymanic Memoryallocation 1
  • 2.
    ⚫ Dynamic memorymanagement refers to manual memory management. This allows you to obtain more memory when required and releaseit when not necessary . ⚫ Although C inherently does not have any technique to allocate memory dynamically, there are 4 library functions defined under <stdlib.h> for dynamic memory allocation. Prepared by : Er. Rhishav Poudyal Dymanic Memoryallocation 2 Function ⚫ malloc() ⚫ calloc() ⚫ free() ⚫ realloc() Use of Function Allocatesrequested size of bytes and returns apointer first byte of allocated space Allocatesspace for an arrayelements, initializes to zero and then returns a pointer to memory deallocate the previouslyallocated space Change the size of previouslyallocated space
  • 3.
    Dymanic Memoryallocation 3 malloc() The namemalloc stands for "memory allocation". The function malloc() reserves a block of memory of specified size and return a pointer of type void which can be casted into pointer of any form. Syntax of malloc() 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. If the space is insufficient, allocation fails and returns NULL pointer. ptr = (int*) malloc(100 * sizeof(int)); This statement will allocate either 200 or 400 according to size of int 2 or 4 bytes respectively and the pointer points to the address of first byte of memory. Prepared by : Er. Rhishav Poudyal Dymanic Memoryallocation
  • 4.
    malloc() example To allocatespace for 100 integers: Prepared by : Er. Rhishav Poudyal Dymanic Memoryallocation int *ip; if ((ip = (int*)malloc(100 * sizeof(int))) == NULL){ printf("out of memoryn"); exit(); } ⚫ Note we cast the return value to int*. ⚫ Note we also check if the function returns NULL.
  • 5.
    Allocating memory fora struct W e can alsoallocate memory for astruct. Example: struct node *newPtr; newPtr = (struct node *)malloc(sizeof(struct node)); Memory allocated with malloc() lastsaslong aswe want it to. It does not automaticallydisappearwhen afunction returns, asautomatic- duration variablesdo, but it does not haveto remain for the entire duration ofyour program, either.There isamechanismto free allocated memory. Prepared by : Er. Rhishav Poudyal Dymanic Memoryallocation
  • 6.
    free() Torelease allocated memoryuse free() ⚫ Deallocatesmemory allocated bymalloc(). ⚫ T akesapointer asan argument. e.g. free(newPtr); Freeingunused memory is agood idea,but it's not mandatory.When your program exits,anymemory which it hasallocatedbut not freed will be automaticallyreleased. Prepared by : Er. Rhishav Poudyal Dymanic Memoryallocation
  • 7.
    free() ⚫Dynamically allocated memorycreated with either calloc() or malloc() doesn't get freed on its own. we must explicitly use free() to release the space. syntax of free() free(ptr); ⚫This statement frees the space allocated in the memory pointed byptr. Prepared by : Er. Rhishav Poudyal Dymanic Memoryallocation
  • 8.
    calloc() ⚫ The namecalloc stands for "contiguous allocation". ⚫ 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. Syntax of calloc() ⚫ ptr = (cast-type*)calloc(n, element-size); ⚫Thisstatement will allocate contiguous space in memory for an array of n elements. Forexample: ptr = (float*) calloc(25, sizeof(float)); Thisstatement allocates contiguous space in memory for an array of 25 elements each of size of float, i.e, 4 bytes. Prepared by : Er. Rhishav Poudyal Dymanic Memoryallocation
  • 9.
    calloc() example /* Usingcalloc() to initialize 100 floats to 0.0 */ #include <stdlib.h> #include <stdio.h> #define BUFFER_SIZE 100 int main(){ float * buffer; int i; if ((buffer = (float*)calloc(BUFFER_SIZE, sizeof(float))) == NULL){ printf("out of memoryn"); exit(1); } for (i=0; i < BUFFER_SIZE; i++) printf(“buffer[%d] = %fn”, i, buffer[i]); return 0; } Prepared by : Er. Rhishav Poudyal Dymanic Memoryallocation
  • 10.
    realloc() ⚫If the previouslyallocated memory is insufficient or more than required, we can change the previously allocated memory size usingrealloc(). Syntax of realloc() ptr = realloc(ptr, newsize); Here, ptr is reallocated with size of newsize. Prepared by : Er. Rhishav Poudyal Dymanic Memoryallocation
  • 11.
    realloc() Ifyou find youdid not allocate enoughspace use realloc(). Y ougive realloc() apointer (such asyou received from aninitial call to malloc()) andanewsize,andrealloc doeswhatit canto give you ablock of memory bigenoughto hold the new size. int *ip; ip = (int*)malloc(100 * sizeof(int)); ... /* need twice as much space */ ip = (int*)realloc(ip, 200 * sizeof(int)); Prepared by : Er. Rhishav Poudyal Dymanic Memoryallocation
  • 12.
    #include <stdio.h> #include <stdlib.h> intmain() { int *ptr, i , n1, n2; printf("Enter size of array:"); scanf("%d", &n1); ptr = (int*) malloc(n1 * sizeof(int)); printf("Addressof previously allocated memory: "); for(i = 0; i < n1; ++i) printf("%ut",ptr + i); Prepared by : Er. Rhishav Poudyal Dymanic Memoryallocation printf(" nEnter new size of array: "); scanf("%d", &n2); ptr = realloc(ptr, n2); for(i = 0; i < n2; ++i) printf("%u t", ptr + i); return 0; }
  • 13.
    printf("Error! memory not allocated."); exit(0); Preparedby : Er. Rhishav Poudyal Dymanic Memoryallocation #include <stdio.h> } #include <stdlib.h> printf("Enter elements of array: "); for(i = 0; i < num; ++i) int main() { { scanf("%d", ptr + i); int num, i, *ptr, sum = 0; sum += *(ptr + i); printf("Enter number of elements: "); } scanf("%d", &num); printf("Sum = %d", sum); ptr = (int*) malloc(num *sizeof(int)); free(ptr); if(ptr == NULL) return 0; { }
  • 14.
    Memory Allocation -calloc() Prepared by : Er. Rhishav Poudyal Dymanic Memoryallocation
  • 15.
    Dymanic Memoryallocation 15 #include <stdio.h> #include<stdlib.h> int main() { int i, num; float *data; printf("Enter total number of elements(1 to 100): "); scanf("%d", &num); data = (float*) calloc(num, sizeof(float)); if(data == NULL) { printf("Error!!! memory not allocated."); Exit(0); } printf("n"); for(i = 0; i < num; ++i) { printf("Enter Number %d:", i + 1); scanf("%f", data + i); } for(i = 1; i < num; ++i) { if(*data < *(data + i)) *data = *(data + i); } printf("Largest element = %.2f", *data); return 0; } Prepared by : Er. Rhishav Poudyal Dymanic Memoryallocation