Dynamic Memory Allocation(in C)-12.03.2015

I’ve decided to keep my “int. to programming” lab’s source files  as blog entries so that i can reach out more easily and that you guys might find them useful as well as my schoolmates.So here’s the source file from today’s class:

#include <stdio.h>
/*dynamic memory allocation functions malloc(),calloc(),realloc()
and free() are defined in stdlib.h library.
malloc(int size)
calloc(int count,size)
realloc(void*pointer,size):you can’t use realloc() function unless you used malloc() or calloc() before.
While these three above for memory assignment free() is a function used to return the memory space.
*/
#include <stdlib.h>
int main(){
int * ptr;
ptr=(int *)calloc(5,sizeof(int));
if(ptr!=NULL)
{
*ptr=1;
*(ptr+1)=2;
//*ptr and ptr[0] are same things.
ptr[2]=4;
ptr[3]=8;
ptr[4]=16;
}
ptr=(int *)realloc(ptr,7*sizeof(int));
if(ptr!=NULL)
{
ptr[5]=32;
ptr[6]=64;
}
//Printing ptr to see if it works.
for(int i=0;i<6;i++){
printf(“ptr[%d]=%d\n”,i,ptr[i]);
}
/*if we don’t use free() function then the memory occupied
by functions realloc and calloc
can’t be used again which isn’t exactly what we want from dynamic memory management functions. */
free(ptr);

getchar();
return 0;
}

Here’s the output:

Adsız

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s