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. 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.

| improve this answer | |
  • Hey, are you saying that when we store variables in stack the memory can overflow due to the no of values since we didn't specify the limit of the memory.And in the case of heap, because we mentioned the exact amount of memory we want to utilise, there is no chance for overflow and it won't return NULL value. – qwerty Oct 31 '16 at 15:36
  • Yes, we can overflow the stack if we don't make sure to read a specific limit. And no, we don't mention the exact amount of memory we want to utilize. We mention the exact size of memory that we want to read at a time. How many times will we read those constant-sized blocks? As many times as we need. If that amount of times represents too much memory, we won't let it be too much. As soon as malloc returns NULL we know we are out of memory and we prompt error and exit the program. – Ricardo David Antonetti Oct 31 '16 at 15:47
  • Hey,instead of using malloc we can give the size of the array at runtime like int a [n], n=getint ().Then what's the difference? – qwerty Nov 3 '16 at 4:32

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .