The variables we have used until now usually had a preset size and were saved either in the globals or in the stack. However it is possible to dynamically allocate memory and adjust the size throughout the code using the functions
realloc. Doing so the chosen amount of sizes will be reserved in the heap and a pointer to the first element will be given.
NOTE: A void pointer
void * is a generic type in C and can be casted into any pointer type. Also note that the allocation functions return
NULL or rather
0 if the requested allocation failed.
size_t n be the amount of elements we want and
char * string be defined already, then the functions are as in following:
void * malloc(size_t size) reserves
size bytes in the heap and returns the address of the first byte. Use:
string = (char *) malloc(n * sizeof(char)).
void * calloc(size_t nitems, size_t size) reserves
nitems * size bytes in the heap and returns the address of the first byte. Use:
string = (char *) calloc(n, sizeof(char)).
void * realloc(void *ptr, size_t size) attempts to resize the memory block pointed by a pointer that was previously allocated with a call to malloc or calloc. Use:
string = (char *) realloc(string, m * sizeof(char)).
void free(void *ptr) deallocates the memory previously allocated by a call to
NOTE: After freeing or until allocating memory, it is recommended to set the pointer
NULL such that you may be able to check easily whether it's allocated or not.