What if your program could grow and shrink its memory exactly when it needs to?
Why dynamic memory is needed - The Real Reasons
Imagine you are writing a program that needs to store a list of names, but you don't know in advance how many names there will be.
You try to create a fixed-size array to hold the names, but sometimes the list is too long or too short.
Using a fixed-size array wastes memory if the list is small, or causes errors if the list is bigger than expected.
Changing the size later is hard because arrays in C have fixed sizes set at compile time.
This makes your program inflexible and prone to crashes or wasted space.
Dynamic memory lets your program ask the computer for just the right amount of memory while it is running.
You can create, resize, and free memory as needed, making your program flexible and efficient.
char names[100]; // fixed size array, may be too big or too small
char *names = malloc(size_needed); // allocate memory dynamically at runtime
Dynamic memory lets your program handle data of any size smoothly and safely during execution.
Think of a contact list app that lets users add as many contacts as they want without crashing or wasting space.
Fixed-size arrays limit flexibility and can waste memory or cause errors.
Dynamic memory allows programs to allocate memory as needed during runtime.
This makes programs more efficient and able to handle varying data sizes.