Exercise 17 – Heap and Stack Memory in C
Hi! Today I worked on Exercise 17: Heap and Stack Memory Allocation, and it was definitely one of the toughest ones so far . This exercise makes a small database program that can store names and emails, but the real focus is on memory allocation – stack vs heap.
What This Program Does
-
Creates a tiny address book database using
struct
. -
Lets us create, set, get, delete, and list records in the database.
-
Introduces file I/O in C (
fopen
,fread
,fwrite
,fclose
). -
Shows how heap memory (malloc) and stack memory are different.
Example Code
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_DATA 512
#define MAX_ROWS 100
struct Address {
int id;
int set;
char name[MAX_DATA];
char email[MAX_DATA];
};
struct Database {
struct Address rows[MAX_ROWS];
};
int main() {
struct Database *db = malloc(sizeof(struct Database)); // Heap memory
if (!db) {
printf("Memory allocation failed!\n");
return 1;
}
// Example entry
db->rows[0].id = 0;
db->rows[0].set = 1;
strncpy(db->rows[0].name, "Rahul", MAX_DATA);
strncpy(db->rows[0].email, "rahul@example.com", MAX_DATA);
printf("ID: %d, Name: %s, Email: %s\n",
db->rows[0].id, db->rows[0].name, db->rows[0].email);
free(db); // Release heap memory
return 0;
}
Heap vs Stack – Easy Way to Remember
Stack
-
Stores local variables (inside functions).
-
Works like a stack of plates → last in, first out (LIFO).
-
Memory is fast but limited.
-
Freed automatically when function ends.
-
Too much use = stack overflow.
Heap
-
Stores dynamic memory (you request it using
malloc
/new
). -
Works like a storage warehouse → you must manage space yourself.
-
Memory is larger but slower.
-
You must free it manually (
free
/delete
). -
Forgetting to free = memory leak.
Shortcut to remember:
-
Stack = Automatic (fast, small)
-
Heap = Manual (big, slow)
Example Output
$ ./ex17 db.dat c
$ ./ex17 db.dat s 1 Rahul rahul@gmail.com
$ ./ex17 db.dat s 2 Daksh daksh@yahoo.com
$ ./ex17 db.dat l
1 Rahul rahul@gmail.com
2 Daksh daksh@yahoo.com
How did I learned it as?
This exercise taught me that:
-
Heap is for big, flexible memory .
-
Stack is for temporary, automatic memory (local variables).
-
Always free your malloc or your program will eat memory forever.
-
Using structs and arrays together makes database-like programs possible even in C.
No comments:
Post a Comment