[comp.unix.aix] problems with variables in C on RS-6000 -- behaving like static

jnl@wjh12.harvard.edu (Joshua Lobel) (04/18/91)

I'm having a problem with the C compiler on a IBM RS-6000 running AIX
3003.

When I run this program on the IBM RISC 6000 the variables in p1 act as if they
have static storage.  Why is this happening?
#include <stdio.h>

p1()
{
char a[5],b[5];
puts(a);
puts(b);
gets(a);
strcpy(b,a);
}

main()
{
p1();
p1();
}

This is the output:
Script started on Wed Apr 17 17:08:36 1991
/u/ts/drs>a.out
pass1
pass1
pass1
pass2

script done on Wed Apr 17 17:08:55 1991

sanders@cactus.org (Tony Sanders) (04/19/91)

In article <593@wjh12.harvard.edu> jnl@wjh12.UUCP (Joshua Lobel) writes:
>When I run this program on the IBM RISC 6000 the variables in p1 act as if they
>have static storage.  Why is this happening?
Because they are on the stack and you are calling the same routine it
works out that 'a' and 'b' get the same storage on the stack (for this
example), thus the value APPEARS to have been saved between calls.  You
should not depend on this behavior.

If you called some other routine that allocated and used automatic
variables the values in 'a' and 'b' would be trashed.  If you WANT it
save the value between calls you should use "static char a[5]...".

For example:
    #include <stdio.h>
    p1() { char a[5],b[5]; puts(a); puts(b); gets(a); strcpy(b,a); }
    p2() { long a,b,c,d,e; a=b=c=d=e=0; }
    main() { p1(); p2(); p1(); }

Now the second time you call p1() the values will most likely be null,
because you change the stack by storing '0' into "a=b=c=d=e".
Again, don't depend on this happening.

-- sanders@cactus.org
I am not an IBM representative, I speak only for myself.
It riles them to believe that you perceive the web they weave,
so keep on thinking free.  -- Moody Blues