A C++ program consists of two .cpp files, main.cpp and f.cpp. Code of the main.cpp file is as follows:
//main.cpp
#include <iostream>
using namespace std;
void f(char* s,int n);
const int N=10;
static char s[N];
static char a[N];
int main ()
{
int i;
for (i=0; i<N; i++)
a[i]='0'+i;
for (i=0; i<N; i++)
cout<<a[i];
cout<<'\n';
f(s,N);
for (i=0; i<N; i++)
cout<<a[i];
cout<<'\n';
}
The function f is defined in the file f.cpp. The program compiles without errors & warnings. When executed, the program regularly ends, leaving the following on cout:
0123456789
!123456789
What’s your comment on validity and behavior of this program? Explain in detail.
I suppose the f function is illegally accessing a’s memory somehow, maybe because s is right before a in memory, so something with indexes occurs… I’m really not sure, however, because I guess static also changes things somehow..
It depends on the compiler. With
gcc-4.3.4, if you can definefas:to produce that output which you have posted. Here is online demo : http://ideone.com/8YT7k
But be warned that such coding is really really bad, and you should not be coding like that, as the actual behavior depends on the compiler, its version, settings, and options.
Whether static arrays are placed near each other or not depends on the compiler, and your program shouldn’t assume that. In this case, however, they are placed adjacent, but then it seems to depend on the other factors. For example, if I print the address of
sandaat the end of your code, without removing anything from your code, thenshas higher address thana, but if I removed your code, thenahas higher address thans. See yourself:shas higher address thana)ahas higher address thans)The first one prints:
but then second one prints this:
So it depends on the compiler’s mood where it places the static arrays!