Why do we use malloc?Is it because storing the value of local variables takes much space in stack and if we store the same value in heap by storing address of that value in stack takes less space?
This is what I understood from that part of CS50:
No, it takes the same amount space in the heap or in the stack. The difference comes when you need to store data dynamically (on user's demand). If you have to store data but you don't know how much data you need to store before the program runs, you can have design problems.
If you have a program storing variable amount of data in a constant size part of the memory in the stack, the program becomes vulnerable to buffer overflow attacks. A user could misuse your program and give too much input. After the stack is overflowed with excess of input, the program can take adjacent data and corrupt it with this user's input. Depending on the size of the buffer overflow and the privileges under which the program was running, the user could take advantage of the overflowed buffer to send commands to control a computer that this user should not be able to control. I had to clear some concepts using this article.
On the other side, if you
malloc constant sized pieces of data in a dynamic manner, you can store information only until you reach the size of the heap (right before the memory overflows). You can check if each piece of data is being stored correctly by checking for
NULL pointers returned by
malloc is going to return
NULL if there is no memory available in the heap. A user might try to overflow it with excess of data but if your program is written defensively, the program is going to stop execution before overflowing (when malloc returns
NULL). There are still threats to heap overflow; you might want to check this article.