The functions to manage heap memory which are included in the directory #include <stdlib.h> are:
malloc():
void * malloc (size_t size);
As we see from the prototype of the malloc function that we have to pass the number of bytes required as parameter to the malloc function and the function returns the starting address of the allocated apace as void pointer. As the void pointer is returned hence we have to typecast the pointer as the type we require. E.g.
If we need 6 bytes for intergers we type cast the memory as
Int* x;
x=(int*)malloc(6);
If we are storing char variables in the allocated space then we do as:
Char* y;
y=(char*)malloc(6);
calloc():
The prototype of the function is as:
void * calloc (size_t nr, size_t size);
nr is number of variables of the required type and size is the number of bytes required for that type
and this function automatically initializes the memory allocated to zero.
e.g.
if we need memory for 6 integers
int* x;
x=(int*)calloc (6, sizeof(int) );
if we need memory for 6 characters
char* x;
x=(char*)calloc (6, sizeof(char) );
NOTE: If any of the two functions is not able to allocate memory then it returns a NULL pointer.
realloc():
The prototype of the realloc() function is
void * realloc (void *ptr, size_t size);
This function is used to redefine the size already allocated. Suppose as I have already allocated memory for 6 integers in the previous example, now I want the space for the 8 integers then I do as:
X= (int*)realloc (x,8) ;
Free():
The prototype of the free() function is
void* free (void* ptr);
We write the following to free the memory of x:
free(x);
Jak odzyskać usunięte SMS – Y z telefonu komórkowego? Nie ma kosza na SMS – Y, więc jak przywrócić SMS – Y po ich usunięciu?
Woow thatt wwas odd. I just wroote an extremely long commment
butt after I clicked submit myy comment didn’t show up. Grrrr…
well I’m not writing alll that oveer again. Anyways, just
wanted to say great blog!
Hi I aam sso happy I found your site, I realy fouhnd you by accident, whiile I
was brfowsing on Bing for something else, Anyhow I am hhere now and would just like tto
ssay thank a lot ffor a tremenndous post andd a aall rpund interesting blog (I alsdo lokve
tthe theme/design), I don’t hzve tike to lookk ver iit aall att tthe miute
butt I have bookmarked it annd alkso added in yur RSS feeds, soo whewn I ave tije I wiill bbe back
to read a lot more, Pleaase do keep up the excelent work.
Your article helped me a lot, is there any more related content? Thanks!
I don’t think the title of your article matches the content lol. Just kidding, mainly because I had some doubts after reading the article.
Your article helped me a lot, is there any more related content? Thanks!