Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Dynamic Memory Allocation in C ~ GNIITHELP

Dynamic Memory Allocation

The process of allocating Memory at runtime is known as dynamic memory allocation. Library routines known as "memory management functions" are used for allocating and freeing memory during execution of a program. These functions are defined in stdlib.h.
FunctionDescription
malloc()allocates requested size of bytes and returns a void pointer pointing to the first byte of the allocated space
calloc()allocates space for an array of elements, initialize them to zero and then return a void pointer to the memory
freereleases previously allocated memory
reallocmodify the size of previously allocated space

Memory Allocation Process

Global variables, static variables and program instructions get their memory in permanent storage area whereas local variables are stored in area called Stack. The memory space between these two region is known as Heap area. This region is used for dynamic memory allocation during execution of the program. The size of heap keep changing.

Allocating block of Memory

malloc() function is used for allocating block of memory at runtime. This function reserves a block of memory of given size and returns a pointer of type void. This means that we can assign it to any type of pointer using typecasting. If it fails to locate enough space it returns a NULL pointer.
Example using malloc() :
int *x;
x = (int*)malloc(50 * sizeof(int)); //memory space allocated to variable x
free(x); //releases the memory allocated to variable x
calloc() is another memory allocation function that is used for allocating memory at runtime. calloc function is normally used for allocating memory to derived data types such as arrays and structures. If it fails to locate enough space it returns a NULL pointer.
Example using calloc() :
struct employee
{
char *name;
int salary;
};
typedef struct employee emp;
emp *e1;
e1 = (emp*)calloc(30,sizeof(emp));
realloc() changes memory size that is already Allocated to a variable.
Example using realloc() :
int *x;
x=(int*)malloc(50 * sizeof(int));
x=(int*)realloc(x,100); //allocated a new memory to variable x

Diffrence between malloc() and calloc()

calloc()malloc()
calloc() initializes the allocated memory with 0 value.malloc() initializes the allocated memory with garbage values.
Number of arguments is 2Number of argument is 1
Syntax :
(cast_type *)calloc(blocks , size_of_block);
Syntax :
(cast_type *)malloc(Size_in_bytes);



This post first appeared on GNIITHELP, please read the originial post: here

Share the post

Dynamic Memory Allocation in C ~ GNIITHELP

×

Subscribe to Gniithelp

Get updates delivered right to your inbox!

Thank you for your subscription

×