Pointers
C Dynamic Memory Allocation
malloc, calloc, or realloc are the three functions used to manipulate memory. These commonly used functions are available through the stdlib library so you must include this library in order to use them.
C – Dynamic memory allocation functions
Function | Syntax |
---|---|
malloc() | malloc (number *sizeof(int)); |
calloc() | calloc (number, sizeof(int)); |
realloc() | realloc (pointer_name, number * sizeof(int)); |
free() | free (pointer_name); |
malloc function
Example program for malloc() in C
Example:
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int main()
{
char *mem_alloc;
/* memory allocated dynamically */
mem_alloc = malloc( 15 * sizeof(char) );
if(mem_alloc== NULL )
{
printf("Couldn't able to allocate requested memory\n");
}
else
{
strcpy( mem_alloc,"w3schools.in");
}
printf("Dynamically allocated memory content : %s\n", mem_alloc );
free(mem_alloc);
}
Program Output:
Dynamically allocated memory content : w3schools.in
calloc function
Example program for calloc() in C
Example:
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int main()
{
char *mem_alloc;
/* memory allocated dynamically */
mem_alloc = calloc( 15, sizeof(char) );
if( mem_alloc== NULL )
{
printf("Couldn't able to allocate requested memory\n");
}
else
{
strcpy( mem_alloc,"w3schools.in");
}
printf("Dynamically allocated memory content : %s\n", mem_alloc );
free(mem_alloc);
}
Program Output:
Dynamically allocated memory content : w3schools.in
realloc function
free function
Example program for realloc() and free()
Example:
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int main()
{
char *mem_alloc;
/* memory allocated dynamically */
mem_alloc = malloc( 20 * sizeof(char) );
if( mem_alloc == NULL )
{
printf("Couldn't able to allocate requested memory\n");
}
else
{
strcpy( mem_alloc,"w3schools.in");
}
printf("Dynamically allocated memory content : " \ "%s\n", mem_alloc );
mem_alloc=realloc(mem_alloc,100*sizeof(char));
if( mem_alloc == NULL )
{
printf("Couldn't able to allocate requested memory\n");
}
else
{
strcpy( mem_alloc,"space is extended upto 100 characters");
}
printf("Resized memory : %s\n", mem_alloc );
free(mem_alloc);
}
Program Output:
Dynamically allocated memory content : w3schools.in
Resized memory : space is extended upto 100 characters
Comments
Post a Comment