C Programming - Memory Allocation - Discussion

Discussion Forum : Memory Allocation - General Questions (Q.No. 3)
3.
How will you free the memory allocated by the following program?
#include<stdio.h>
#include<stdlib.h>
#define MAXROW 3
#define MAXCOL 4

int main()
{
    int **p, i, j;
    p = (int **) malloc(MAXROW * sizeof(int*));
    return 0;
}
memfree(int p);
dealloc(p);
malloc(p, 0);
free(p);
Answer: Option
Explanation:
No answer description is available. Let's discuss.
Discussion:
25 comments Page 1 of 3.

Vishal Dalawai said:   1 decade ago
@Murugan.

Below i have wrote code for memory allocation & free for 2-D array(3 Rows, 4 Columns)

#include<stdio.h>
#include<stdlib.h>

#define ROW 3
#define COL 4

int main()
{
int i;
int **arr;

// Memory allocation for Rows..
arr = (int**)malloc(ROW*sizeof(int*));
if(arr == NULL)
{
printf("Memory allocation for Row failed..\n");
exit(1);
}

// Memory allocation for Columns..
for(i=0; i<ROW; i++)
{
arr[i] = (int*)malloc(COL*sizeof(int)); // each row having 4 cols
if(arr[i] == NULL)
{
printf("Memory allocation for Column Elements failed..\n");
exit(1);
}


// Memory Free..
for(i=0; i<ROW; i++)
free(arr[i]);

free(arr);

return 0;

}

Emanuel said:   9 years ago
I don't understand the casting (int**). The malloc function gives an address of memory where you can put an integer value, i.e., it is a pointer to an integer. How it can help a cutting that it points to a pointer to an integer. It, indeed, only a pointer to an integer?

Ahmed said:   9 years ago
I knew the answer, the type casting in malloc because malloc returns a void pointer. So we should type cast it to the type we want to use first!

Darshan kg said:   9 years ago
Malloc allocates a single block of memory but calloc allocates multiple blocks of memory. For calloc block, initial value will be zero.

Sai ram said:   2 decades ago
Any allocation functions like alloc () , malloc () and calloc () should release their memory space with free () function only.

Manojkumar said:   1 decade ago
Yeh any allocation functions like alloc() , malloc() and calloc() should release their memory space with free() function only.

Roddur said:   7 years ago
why are we doing malloc(.... sizeof(int*))?

It won't only (int ) do in place of (int *)?

Please anyone explain me.

Abhishek said:   1 decade ago
It is a pointer to a pointer, means it keeps the address of a pointer variable.

Ex: int *q, **p;

Then p = &q;

Sha Vat said:   8 years ago
Here, free() function is used to clear the memory that is dynamically created using calloc(), malloc() functions.

Ahmed said:   9 years ago
Same problem here, why the type casting (int**)?

p = (int **) malloc(MAXROW * sizeof(int*));


Post your comments here:

Your comments will be displayed after verification.