0
Can anyone explain me syntax of malloc ( ), calloc( ), realloc( )? And how exactly it works.
I am not getting how malloc, calloc, realloc works. Please explain me in simple words as I am beginner !
5 Answers
+ 9
malloc() will just reserve a contiguous block of memory (in this case 200 bytes if sizeof(int) = 4). (int*) tells the compiler that you are going to use this memory block to store integers
+ 4
If you want to allocate memory for 50 integers using malloc(), the syntax is
int *nums = (int*)malloc(50*sizeof(int));
You know that it worked if the result is not a null pointer:
if(nums == NULL) {
// something went wrong
}
You can combine those to steps like this:
int *nums;
if((nums = (int*)malloc(50*sizeof(int))) != NULL) {
// do something with the allocated memory
} else {
// failed to allocate memory
}
calloc() basically does the same as malloc() but it will set the allocated memory to 0, and the syntax is slightly different:
int *nums = (int*)calloc(50, sizeof(int));
realloc() reallocates memory that was allocated with malloc or calloc before.
If you're running out of memory and want to reallocate memory for 50 more integers, the syntax would be
nums = realloc(nums, 100*sizeof(int));
To free the memory and avoid memory leaks, use free(nums); when you don't need the allocated memory any longer.
+ 1
It is hard to me to get it !
Please explain me in simple words.*AsterisK*
+ 1
Thanks Anna
But what is meaning of this
ptr = (int*) malloc (50*sizeof(int));
What is meaning of return type int* here.
What are the behind the scenes!