Saturday, January 31, 2009

extern pitfalls in G++

Look at the example:
unit1.cpp

#include <iostream>
using namespace std;

int I = 2;
extern const int J = 10;
void FuncI();
void FuncJ();


int main()
{
cout << hex;
cout << "I, before " << I << " " << *(&I + 1) << endl;
FuncI();
cout << "I, after " << I << " " << *(&I + 1) << endl;
FuncJ();
}


unit2.cpp

extern long long I;
extern int J;


void FuncI()
{
I = I << 36;//causes contiguous memory damage
}


void FuncJ()
{
J++;//causes segmentation fault
}


The program compiles fine and the results are:

I, before 2 0
I, after 0 20
Segmentation fault


Why g++ compiler is so spoiled here. I don't know. In Visual Studio it's impossible to do such nasty things.

No comments:

Post a Comment