How is dynamic memory allocation handled in ‘C’? In your own words
name and describe the functionality of each of the functions involved.
During runtime
- The memory is allocated from the heap
- Allows a program to manage a variable amount of memory rather than relying on fixed memory allocated at compile time.
The standard C library provides 4 primary functions to manage memory dynamically:
malloc: Allocates a block of uninitialized memory of a specified size and returns a void * pointer to the start of the block
calloc: Allocates an array in memory for a specified number of elements with all bits initialized to 0, also returns a void * pointer
realloc: Changes the size of a previously allocated block of memory, takes the old pointer and the new size.
free: Releases the dynamically allocated memory back to the system’s heap. Crucial for preventing memory leaks
What is the purpose of the stack in ‘C’? Illustrate your answer with code
snippets. What are the advantages and disadvantages of using the
stack?
The stack stores function call frames, including local variables, function parameters, and return addresses, and is automatically managed using a LIFO discipline.
Example:
```java
int add(int a, int b){
int sum = a + b; // local variable on the stack
return sum;
}
~~~
Advantages:
Disadvantages:
What are the two ways that memory management is handled in ‘C’? Describe
the advantages and disadvantages of both of them.
malloc, calloc, realloc, and free.