System Design and Analysis - Dynamic Memory Allocation
System Design and Analysis - Dynamic Memory Allocation
Syntax:
ptr=(cast-type*)malloc(byte-size);
Example:
int *ptr;
ptr=(int*)malloc(100*sizeof(int));
This statement will allocate either 200 or 400
according to size of int 2 or 4 bytes respectively and
the pointer points to the address of first byte of
memory.
Code Example of malloc()
Problem:
Syntax:
ptr=(cast-type*)calloc(no_of_blocks, size_of_each_block_in_bytes);
Example:
float *ptr;
ptr=(float*)calloc(25, sizeof(float));
This statement allocates contiguous space in
memory for an array of 25 elements each of size of
float, i.e, 4 bytes.
Code Example of calloc()
Problem:
Example:
free(ptr);