Nils O. Selåsdal said:
Hi guys,
Consider the following piece of code:
func()
{
if(x==0) {
int arr[50];
/* do something */
}
else {
int arr2[100];
/* do something */
}
}
I wanted to know, if the space of arr[50 is allocated only when the
condition "x==0" is
true or the space is allocated when the function "func" is called.
I am working on an m68k implementation where the local varialbles are
allocated
on stack. I would be really grateful if anyone can provide me an
answer for an m68k
The answer would be compiler dependant, compiler flags dependant, and
code dependant. Some code , depending on the optimizations/etc. might be
reordered to play things out very differently than just some very
slightly different code.
Your best bet is to peek at the assembly(if available - gcc -S for gcc)
generated for the exact code you have compiled with the options you'll
be using in "production".
Another approach would be to examine the addresses of the array
objects, either using printf with a "%p" format (and the required cast
to void*) or a debugger. With some reasonable assumptions about how
memory is allocated, this should tell you what you need to know.
But of course the results will be specific to whatever compiler you're
using, and possibly to the options with which you invoke it.
The answer is unlikely to depend on the fact that you're using an
m68k. Different compilers for the same CPU are free to do this
differently; so is the same compiler with different options.
If your compiler allocates 150 bytes for arr and arr2 (with
appropriate optimization options), consider complaining to your
vendor. It's not a violation of the standard, but it's a waste of
space since arr and arr2 cannot exist simultaneously.
A compiler could reasonable allocate max(sizeof arr, sizeof arr2) on
entry to the function, or allocate just enough for a single array on
entry to the block contaiing its declaration. The latter saves space
in some cases at the expense of some extra code.
If you're desparate for space *and* your compiler doesn't do the
optimization you need, you can combine the declarations yourself,
being careful to guarantee that you always allocate enough space for
the object you need. The simplest way to do this would be to put arr
and arr2 in separate functions, though that imposes some additional
overhead as well.
Discussion more detailed than this should probably go to
comp.arch.embedded or to some system-specific newsgroup.