My question is in what order the global variables are stored in the memory.
For the above example, from the output of size command 18 is the total size of the global variables and when the strcpy statement is executed, it is overwriting the first character of string2 with NULL in order to terminate string1 with NULL.
So, how the variables got stored in memory?
1) Is string1 followed by string2?
2) Is string2 followed by string1?
This should print the starting address of the two strings. Run the program several times and see if you can get any pattern (of memory allocation) from that.
Just tried this on a FreeBSD system. The addresses allocated are the same every time, as no other memory is allocated in the interval between program runs.
Also, the allocation is in the order that is specified in the program. i.e. string2 is allocated a starting address that is (12 bytes) before that of string1.
Why exactly are you interested in knowing the order of allocation of the variables?
then the starting address of string1 may change, depending on your system's architecture. You cannot depend on the starting position of objects in memory.
This is because the compiler may adjust the starting byte of string1 to match the addressing scheme your system uses. Or to optimize access to the object.
I got the answer by analyzing all the replies from you.
I used the fprintf statement to know the starting address of the strings.
On my m/c, I found that it is storing string1 first and then string 2.
So, after executing strcpy(string1,"******") statement it is rewriting the first character of string2 with NULL in order to terminate string1 as strcpy does.
Is the order of storing is OS dependent or compiler dependent ?