S
Spiros Bousbouras
Hello,
I'm confused about heap and stack memories management in C language.
C language (as specified by the standard) doesn't say anything
about stack or heap and their management. Specific implementations
might worry about such issues if they are relevant to the platform on
which they run.
Most
books explain that local stack variables for each function are automatically
allocated when function starts and deallocated when it exits.
Which books are those ? Do they claim to speak on standard C or
C on specific operating systems ?
In contrast,
malloc() always takes memory in the heap.
When you say always do you mean on every operating system
on every platform which has a C compiler ? I doubt that this
is true.
Now, let's consider the code as
follows:
int get_buffer()
{
unsigned int head; // local variable?
char *buf; // also local?
If by "local" you mean automatic then the answer is yes.
In other words you won't be able to access the values of
the variables head and buf after the function exits.
char = malloc(100); // allocate memory from heap
I will assume that you meant to write buf instead of char.
There are no guarantees that the memory will be allocated
from the heap or even that such a thing exists on your
platform.
...
}
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?
If you happen to be running the above programme on an
operating system where heap and stack are meaningful
terms then it is likely that buf will be allocated on the
stack and buf from the heap. Let's say that a memory segment
of size of at least 100 bytes is allocated starting at the
address A000. Then the value A000 will be stored in the
area of memory allocated for buf. Note that we have 2
different things here : one is the actual memory which
starts at the address A000 and the other is the value
A000 which can be stored somewhere else , perhaps on
the stack if such a thing exists. In any case for the vast
majority of C programmes you need not worry whether
the memory is allocated on the stack or heap or whatever.
If you think you need to worry then you have probably
misunderstood something.
Is this
true, that whenever we call malloc (inside of function or outside), we get
memory from heap?
Unknown. And for most C programmes you needn't worry
about it.