Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 165
  • Last Modified:

What does free() actually do ?

I create a double dimensioned array of int elements and allocate memory to it : -

int **arr;
int x,y;
x = 4;
y = 5;
arr = malloc(x*(sizeof(*arr)));
for (i=0;i<x;i++)
{
arr[i] = malloc(y*sizeof(**arr));
}


Then I enter the values in the array.
And then ... free the array : -

for (i=0;i<x;i++) free(arr[i]);
free(arr);

After freeing i print the array and the i still get the values.
Does free() wipes off the allocated memory ?
Does free() sets the pointer to NULL ?
Or it justs flags the allocated memory in a way so that it can be allocated to some other pointers ?

Kindly help
thanks already.

Dhritiman


0
Dhritiman
Asked:
Dhritiman
1 Solution
 
umangjoshiCommented:
pls declare like this

int *nos[10];
int no_of_cols = 5;
nos[0] = (int *)malloc(no_of_cols * sizeof(int));
nos[1] = (int *)malloc(no_of_cols * sizeof(int));
0
 
akshayxxCommented:
>>>After freeing i print the array and the i still get the values.

yes u can because what free does is that it marks the memory pointed to .be available for further allocation calls...

>>>Does free() wipes off the allocated memory ?

 it doenst wipe of .. just marks it as free for allocation ..

>>>Does free() sets the pointer to NULL ?

NO it doesnt ..

>>>Or it justs flags the allocated memory in a way so that it can be allocated to some other pointers ?

yes you got it here
0
 
rajeev_devinCommented:
No the free does not sets memory to NULL. Infact it just releases the allocated memory to the operating system. So that the released memory can be allocated next for another request. Another thing is that you have not done any explicit typecast. In all compilers it will not compile. Try to do typecast. Your some statements, I think, is not correct

     int x,y;
     x = 4;
     y = 6;
     arr = (char **) malloc(x*sizeof(char *));
     for (i=0;i<x;i++)
     {
          arr[i] = (char *) malloc(y*sizeof(char));
     }
// Do your work here
 
     for (i=0;i<x;i++) free(arr[i]);
     free(arr);

Just compare the statements...
Give further comments...

0
 
jmcgOwnerCommented:
Nothing has happened on this question in over 10 months. It's time for cleanup!

My recommendation, which I will post in the Cleanup topic area, is to
accept answer by akshayxx.

PLEASE DO NOT ACCEPT THIS COMMENT AS AN ANSWER!

jmcg
EE Cleanup Volunteer
0

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Tackle projects and never again get stuck behind a technical roadblock.
Join Now