(e-mail address removed) a écrit :
This is an interview question and I gave out my answer here, could you
please check for me?
Q. What are the memory allocation for static variable in a function,
an automatic variable and global variable?
My answer: static variable in function and global variable are
allocated in head, and automatic variable is allocated in stack.
Right?
Maybe you mean "heap" not "head" ???
If that is the case, you are mostly right, it depends on the
implementation and OS running, etc.
A program has a fixed area with the initial data of the program.
This is not the heap in the traditional sense but just a RAM space
filled with tables, strings, double data, etc.
The heap is a variable area used to allocate space for data
dynamically during program execution. That data can be
local to a function, or be global. You are confusing the scope
of a variable, and the place where it is allocated, what is
not the same.
{
char *m = malloc(2678);
// use of m
free(m);
}
m is allocated from the heap, but it is local to that block
since it is freed before the block is finished. The varible
"m", of pointer type, is local to that block, and is active
only when that block is active.
Mostly, local variables are allocated from the stack, but some
people here say there are machines without stack that implement
C. I do not know, I have never seen one of those. In any
case in most systems, the stack exists and it is used to
allocate local variables.