Bogdan said:
I had during an interview this question: which variables are
allocated on the stack in a function ? I am unsure how the output
variable is handled. Is this one too allocated on the stack and popped
when the function exists ?
Here is an example:
char* some_function(char c)
{
char *out = malloc(10);
return out;
}
On the local stack are there one char and 2 pointers to chars ?
This can actually be a clever question, at least if it's meant
to test your understanding on several levels (assuming that the
person asking it is aware of that).
The correct answer to the question (unless further qualified)
is, of course, that it's impossible answer it. The C standard
doesn't mandate the existence of a "stack", "heap" etc. (none
of these words appear in the standard at all). It is left to
the discretion of the compiler where it gets the memory needed
from.
On the other hand on all machines I am familiar with compilers
use a stack and a heap. And (non-static) local variables like
'out' are allocated (if necessary) on the stack (while alloca-
tions with malloc() are made from the heap).
Things get even more interesting since there is a chance
that a local variable actually might not reside in memory at
all, e.g. in this function the compiler (at least when allowed
to do a bit of optimization) might rather likely not need room
on the stack for 'out' but will be able to get along with a CPU
register - the function could easily rewritten as
char * some_function( char c )
{
return malloc( 10 );
}
and then there's no 'out' variable left.
The next question is how values are passed between the caller
and the function. In the simplest case (again, on machines one
typically encounters - remember that there is no requirement
that a stack exists at all) arguments and return values are
put on the stack. But if there aren't too many of them the
compilers often passes them in CPU registers. Thus for the
function there is a good chance that neither 'c' nor 'out'
ever make it to the stack and instead just reside in CPU
registers (which, again, might depend on the settings for
the compiler, gooogle for e.g. "calling convention").
So, except for the first statement that the question, can't
be answered, it all depends on how the compiler works (and
the architecture the program is compiler for). It only can
be determined for sure by inspecting the assembler code the
compiler generates. But that, of course, is then not a
question about C but about the way a certain compiler im-
plements what is required by the C standard (though it's
also an interesting question that a compentent C programmer
is not unlikely to at least have spend a bit of time won-
dering about).
Regards, Jens