Understanding Heap and Stack in C Programming
What is Heap?
Heap refers to a region of memory used for dynamic allocation during program execution. It is typically larger than stack memory and is allocated when the program starts.
Usage of Heap
- The heap is primarily used for storing complex data structures such as dynamically allocated arrays or structs.
- Memory allocated on the heap must be manually freed to prevent memory leaks.
Example code:
#include <stdio.h>
#include <stdlib.h>
int main() {
int *array = (int *)malloc(5 * sizeof(int));
if (array == NULL) {
perror("Failed to allocate memory");
return 1;
}
array[0] = 10;
array[1] = 20;
printf("Value at index 0: %d\n", array[0]);
free(array);
printf("Value at index 1 after freeing: %d\n", array[1]);
return 0;
}
Output:
Value at index 0: 10
Value at index 1 after freeing: 0
What is Stack?
Stack is a memory area used for storing function calls and local variables. Its size is usually fixed and limited, and it keeps track of the execution state of a program.
Stack in Function Calls
- The stack holds context information for function calls, including parameters, local variables, and return addresses.
- Data stored on the stack has a short lifetime and is automatically deallocated upon function completion.
Example code:
#include <stdio.h>
void exampleFunction() {
int localValue = 5;
printf("Local value: %d\n", localValue);
}
int main() {
exampleFunction();
return 0;
}
Output:
Local value: 5
Stack in Multithreading
- Multiple threads can be created where each runs its own stack.
- Each thread’s stack is independent and allows concurrent execution.
Example code:
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#define THREAD_COUNT 3
void* workerThread(void* arg) {
int id = *(int*)arg;
printf("Thread %d is executing\n", id);
return NULL;
}
int main() {
pthread_t threads[THREAD_COUNT];
int ids[THREAD_COUNT];
for (int i = 0; i < THREAD_COUNT; i++) {
ids[i] = i;
pthread_create(&threads[i], NULL, workerThread, &ids[i]);
}
for (int i = 0; i < THREAD_COUNT; i++) {
pthread_join(threads[i], NULL);
}
printf("All threads completed\n");
return 0;
}
Output:
Thread 0 is executing
Thread 1 is executing
Thread 2 is executing
All threads completed
Summary
- Heap and stack are distinct memory regions in C with different purposes and management styles.
- Heap supports dynamic allocation and requires manual memory handling.
- Stack handles function calls and local variables with automatic allocation and deallocation.
- Choosing between heap and stack depends on the scope and lifecycle of data.
- Proper memory management is essential to avoid issues like memory leaks and dangling pointers.