Reg. Local vs Global declarations

Please go through the following two versions of code :-

Version 1 --- string1 and string2 declared as Global variables
The output is :-- (as expected sprintf is overwriting the first byte of string2 with NULL)
string1=send
string2=

#include <stdio.h>
char string1[4];
char string2[5];
main()
{

strcpy(string2,"test");
sprintf(string1,"%s","send");
printf("string1=%s\n",string1);
printf("string2=%s\n",string2);
}

Version 2 --- string1 and string2 declared as Local variables
The output is :--(Is sprintf is terminating string1 with NULL or not?)
string1=send
string2=test

#include <stdio.h>
main()
{
char string1[4];
char string2[5];

strcpy(string2,"test");
sprintf(string1,"%s","send");
printf("string1=%s\n",string1);
printf("string2=%s\n",string2);
}

Is there any difference b/w memory allocation in Local and Global declarations.

Thanks for ur suggestion in advance.

This depends on a lot of things like architecture, compiler, options, etc.

What architecture are you on ?

Version 1 --- string1 and string2 declared as Global variables
The output is :-- (as expected sprintf is overwriting the first byte of string2 with NULL)
string1=send
string2=

This need not happen becaus string2 comes before string1 (lower)
in memory (on PC linux and many architecutres), so the output is
string1=send
string2=test.

If the space allocated for string2 is too short, you will see
something like:
string1=send
string2=testsend

The space allocated for string1 does not change anything for this test.

Besides, use
sprint("%x", string1)

to see where the string space are allocated; try it with various array length, you will see that sometimes
the compiler leaves much more space than required between the too string,
may be for optimization related questions, be it on the heap or on the stack, so that it may well work even if the allocation is buggy.

HTH, else precise architecture, compiler etc.

samuel

Thanks.

As u mentioned, it depends on arch., comp,... B'se I am also getting diff. o/p on Linux m/c.

Actually, my environment is : Sun OS 5.8 on Sun SPARC arch.

My observation is as follows( on solaris):

1) For the global case : allocation is string1 first and then string2
2) For the local case :
PUSH string1
decrement SP
PUSH string2
and hence string2 first and then string1

Once again, thanks for ur time.