Search code examples
cmallocfreestack-overflow

What is a stack and why is malloc prevent it from overflowing?


Possible Duplicate:
What and where are the stack and heap

I am new in C language, I mostly use Python for daily usage, so I am not very familiar with these concept. The previous question I asked here: Big array gives segmentation error in C leaded me to this question. So, what is a stack, and what the relation of malloc to it?


Solution

  • Read about stack and heap here: http://ee.hawaii.edu/~tep/EE160/Book/chap14/subsection2.1.1.8.html .

    malloc allocates memory from the heap and not the stack (Read about stack and heap). That is why it prevents the stack from overflowing :) . When you declare an array of long long type, it has a fixed size allocated to it and that memory is taken from the stack.But malloc allocates size dynamically based on your requirement (ie number of elements required to be stored in the array).

    PS: In python memory allocations are taken care for you. You are pampered as a programmer :D . C is closer to the system and so you must have a fair amount of system knowledge to understand the working of C better.