Dynamic memory allocation in C

From Embedded Systems Learning Academy
Revision as of 16:15, 27 April 2017 by Proj user6 (talk | contribs)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

Malloc ,Callloc, Realloc, free:

1) Malloc: Malloc dynamically allocates requested memory and returns pointer to it.

/* We are allocating memory for "n" integers and returns integer pointer */
int *ptr = (int *) malloc(n * sizeof(int)); // We have type casted pointer to int

2) Calloc: Calloc dynamically allocates requested memory and initializes it to zero. Calloc is compiler independent.

/* We are allocating memory for "n" integers and returns integer pointer */
int *ptr = (int *) calloc(n,sizeof(int)); // We have type casted pointer to int

3) Realloc: Realloc is used when we have dynamically allocated memory and need to resize it. Realloc can be used as a substitute to malloc or free.

int *ptr1 = (int *) realloc(ptr ,4*n*sizeof(int));  //dynamically allocated memory by malloc at pointer "ptr" will be increased 4 times in size.
ptr1 = (int *)realloc(ptr1,0); //use realloc as free
int *ptr2 = (int *)realloc(NULL,n*sizeof(int)); //used as malloc


4) free:

After use of dynamically allocated memory, free the memory.
Consider below example:

free(ptr); // space pointed by pointer "ptr" is made available but the content in space is unchanged.
ptr = NULL;// NULL represents address 0 and it can not be dereferenced so ptr can not be dereferenced.