Re: stack and heap
- From: Logan Shaw <lshaw-usenet@xxxxxxxxxxxxx>
- Date: Tue, 26 Jun 2007 00:29:08 -0500
Roman Mashak wrote:
I'm confused about heap and stack memories management in C language. Most books explain that local stack variables for each function are automatically allocated when function starts and deallocated when it exits. In contrast, malloc() always takes memory in the heap. Now, let's consider the code as follows:
int get_buffer()
{
unsigned int head; // local variable?
char *buf; // also local?
char = malloc(100); // allocate memory from heap
...
}
Here is confusion: "char *buf" is supposed to be allocated in stack, on the other hand, malloc() get memory from heap? How to understand this?
That's a good question, and luckily it's not too hard to see why.
The answer is that at this point, right after you have called malloc(),
there are actually TWO pieces of memory that have been allocated.
On a typical 32-bit system, there is a 4-byte region allocated for
the pointer (for "buf"), and those bytes come from the stack. Then
there is a second 100-byte region allocated from the heap. There is
no variable name for this 100-byte region, though. (That is part of
why you have to keep track of the memory yourself and remember to
deallocate it.)
> Is this
> true, that whenever we call malloc (inside of function or outside), we get
> memory from heap?
Yes, malloc() will always return memory from the heap. It doesn't
depend on where it's called from. (Technically, it could use some
other data structure to maintain the pool of memory that it draws from,
but it's still informally called "the heap" even if that's true.)
- Logan
.
- References:
- stack and heap
- From: Roman Mashak
- stack and heap
- Prev by Date: Re: Poker Hand recognition! -CHALLENGE-
- Next by Date: Data structures for checking consistency of a partial order?
- Previous by thread: stack and heap
- Next by thread: Re: stack and heap
- Index(es):
Relevant Pages
|