Dynamic memory allocation Flashcards
types of memory in c
static memory
dynamic memory
Dynamic memory allocation
it is a way to allocate memory to a datastructure during the runtime
Functions used for DMA
-malloc()-memory allocation
-calloc()-continous allocation
-free()
-realloc()-re allocation
malloc()
takes a number of bytes to be allocated and returns a pointer of type void
ptr=(int) malloc(5sizeof(int));-here void pointer is typecasted into int pointer
have to include <stdlib.h> library</stdlib.h>
if the give memory size is out of your systems capability then the malloc returns null to the pointer
ptr[0]=1;
ptr[1]=2;
ptr[2]=3;
calloc()
continuous allocation
-initializes with 0
ptr=(int*) calloc(5,sizeof(int));
free()
-we use it to free memory that is allocated using malloc and calloc
when a variable(int) is statically allocated then after its use then the memory is freed up automatically which is not in dynamic memory
free(ptr);
realloc()
reallocate the (increase of decrease ) the memory using the same pointer and size
ptr=realloc(ptr,newsize);
we cannot do this with array only with dynamically allocated memory