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?
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.
malloc allocates space on the heap, not on the stack.
The stack is the space used for the local variables and parameters for each function.
In other words, every function uses the stack for local variables. Malloc uses memory on the heap which is completely different.
wiki has a nice explanation for call_stack.
malloc
help you to apply for memory from the system, which allocates on heap
.
上一篇: 什么是尾巴呼叫优化?
下一篇: 什么是堆栈,为什么malloc防止溢出?