CodesJava

Easy learning with example program codes

C Dynamic memory allocation


In Static Memory Allocation, memory is allocated at compile time, that can’t be modified while executing program and is generally used in array.

In Dynamic Memory Allocation, memory is allocated at run time, that can be modified while executing program and is generally used in linked list.

Methods used for Dynamic memory allocation:

Method Syntax Uses
malloc() P = (cast_type*) malloc(byte_size) To allocate a single block of requested memory.
calloc() P = (cast_type*) calloc(number, byte_size) To allocate multiple block of requested memory.
realloc() P = realloc(P, new_size)

 

To allocate the memory occupied by malloc() or calloc() function.
free() free(P)

 

To free the dynamically allocated memory.

 

Example:

#include<stdio.h>
#include<stdlib.h>  
 
void main()
{  
int n = 10;  
int *a, *b;
a = (int*)malloc(n*sizeof(int));
printf("current address = %x \n",a);
 
b = (int*)calloc(n,sizeof(int));
printf("current address = %x \n",b);
}

Output

current address = 3acba260
current address = 3acbb2a0
Posted in C   
Sign Up/ Sign In
Ask a Question


Copyright © 2018 CodesJava DMCA.com Protection Status SiteMap Reference: Java Wiki