Dynamic memory allocation in C

From Embedded Systems Learning Academy
Revision as of 19:43, 16 December 2016 by Proj user14 (talk | contribs) (Created page with "Malloc ,Callloc, Realloc, free: 1)Malloc: Malloc dynamically allocates requested memory and returns pointer to it. <syntaxhighlight lang="c"> /* We are allocating memory for...")

(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 beused as a substitute to malloc or free.

(void*) realloc(void *ptr ,sizeof(int));


4)free:

After use of dynamically allocated memory, free the memory. Consider below example: int *ptr = (int *) malloc(n * sizeof(int)); //Use dynamically allocated memory

free(ptr); ptr = NULL;// NULL represents address 0 and it can not be dereferenced so ptr can not be dereferenced.