I was watching the week 5 lecture and David said that a chunk of memory can be allocated two ways:

  1. using malloc();
  2. declaring an array of a certain size (char buffer[10]).

Is there really any difference between the two? Does the second method need to use free(), or only when malloc() is used?


yes, indeed there is a difference! when you use malloc, the block of memory that you are trying to allocate gets allocated in a region of memory called the heap. freeing memory allocated on the heap has to be done manually (by calling free).

when you declare an array of a certain size, depending on where you declare your array, the memory for it may get allocated on the stack (e.g., if it's declared as a local variable — inside of a function) or on a data segment (e.g., if it's declared as a global variable).

memory allocated on the stack gets freed automatically as your array (or more generally, local variable) gets out of scope. so you don't have to worry about manually freeing your memory.


For most purposes you probably won't experience any differences between the 2, but the difference is that declaring an array such as char buffer[n] results in memory on the stack being allocated. Stack memory is smaller, and is cleared after the function returns; so if you need to retain buffer, or if buffer is so large as to exceed stack memory capacity, better to malloc memory. Malloc is allocated memory on the heap, which is much larger and will only be freed by explicitly calling free. Downside is that this process is slower.

You must log in to answer this question.

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