How will you free the allocated memory ? code example
Example 1: how to dynamically allocate array size in c
// declare a pointer variable to point to allocated heap space
int *p_array;
double *d_array;
// call malloc to allocate that appropriate number of bytes for the array
p_array = (int *)malloc(sizeof(int)*50); // allocate 50 ints
d_array = (int *)malloc(sizeof(double)*100); // allocate 100 doubles
// use [] notation to access array buckets
// (THIS IS THE PREFERED WAY TO DO IT)
for(i=0; i < 50; i++) {
p_array[i] = 0;
}
// you can use pointer arithmetic (but in general don't)
double *dptr = d_array; // the value of d_array is equivalent to &(d_array[0])
for(i=0; i < 50; i++) {
*dptr = 0;
dptr++;
}
Example 2: what happens if we don't free dynamically allocated memory
But the memory allocation using malloc() is not de-allocated on its own.
So, “free()” method is used to de-allocate the memory. But the free()
method is not compulsory to use. If free() is not used in a program the
memory allocated using malloc() will be de-allocated after completion
of the execution of the program