Memory short qs Flashcards

(3 cards)

1
Q

How is dynamic memory allocation handled in ‘C’? In your own words
name and describe the functionality of each of the functions involved.

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

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?

A

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:

  • automatic and fast memory allocation/deallocation
  • No manual memory management required

Disadvantages:

  • Limited size ( risk of stack overflow)
  • Not suitable for large or long-lived data.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What are the two ways that memory management is handled in ‘C’? Describe
the advantages and disadvantages of both of them.

A
  1. Automatic (stack) memory managementMemory for local variables is allocated on function entry and freed automatically on function exit.
    • Advantages: Fast, simple, no risk of memory leaks
    • Disadvantages: Limited size, short lifetime, not suitable for large or long-lived data
  2. Dynamic (heap) memory managementMemory is allocated and freed explicitly using malloc, calloc, realloc, and free.
    • Advantages: Flexible size, lifetime controlled by the programmer, suitable for large data structures
    • Disadvantages: Slower, risk of memory leaks and dangling pointers if mismanaged
How well did you know this?
1
Not at all
2
3
4
5
Perfectly