#include<stdlib.h>
malloc
allocate length of n blocks in the heap
malloc(int size);
malloc(100) // allocate 100 byte in the heap
void *
, int *p=(int *)malloc(1)
// p is the pointer, allocate 1 byte in the heap
// however, if we want to store value 1 in the *p, since int is 4 byte, there are 3 byte is lost. to solve the problem, please use this :
int *p=(int *)malloc(sizeof(int)*100);
// in this way, allocate 100 int space in the heap, so it can store 100 integer.
free
release the spacewhen we don’t use the space that we allocated using malloc
, we need to release the space.
// void free(void *ptr)
int *p=(int *)malloc(sizeof(int)*5);
free(p)
realloc
change the size of the memory block pointed by ptrvoid *realloc(void * ptr, size_t size)
int *p=(int *)malloc(sizeof(int)*10);
int *a=(int *)realloc(p,sizeof(int)*20);
if (a==p){
printf("there is no change in the address");
}
else{
printf("there is change in the address");
}
tech — Feb 22, 2024
Made with ❤ and at Earth.