Click here to Skip to main content
15,906,645 members
Please Sign up or sign in to vote.
2.00/5 (1 vote)
See more:
Hi All,
I have doubt in that how the malloc function will allocate memory for the pointer

if i done like that(following)

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

it allocate a memory..

but i use some memory only in that.. i want to delete or free the unused memory .

Please give me a suggestions.

Thanks in Advance.
Posted
Updated 21-Jun-11 18:47pm
v2

You can use the realloc function for that purpose
http://msdn.microsoft.com/en-us/library/xbebcx7d.aspx[^]
Anyway, it is preferable to know the exact size in advance.
 
Share this answer
 
v2
Allocating memory on heap (256 integers in example):
int size = 256; //<-- Can be whatever you need (doesn't have to be a hard coded constant, could be some variable that's evaluated at run time)

//Using malloc/free
int *iArray;
iArray = (int *) malloc(size*sizeof(int));  //Allocate (requires size in bytes, hence the sizeof() call)

//To check if valid and take appropriate action
if(iArray == NULL)
{
  printf("Error: Failed to allocated required memory.");
  exit(1);
}

//... Use
free(iArray);                               //Deallocate when done
 
Share this answer
 
v4
Hope this[^] might help you.
 
Share this answer
 
Comments
Albert Holguin 22-Jun-11 14:35pm    
that's a nice, complete explanation as to using pointers... my 5

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900