2

I was struggling with segmentation fault after returning from main in C++0x code compiled under GCC with MinGW, and have narrowed it to simple case:

class A {
public:
    virtual ~A();
};

A::~A() {
}

const A a;

int main() {
    return 0;
}

The reason is correlated with:

  1. const qualifier before object, removing it stops seg fault,
  2. Lack of constructor in class A - adding empty one stops seg fault.
  3. Version of compialtor - newer TDM MinGW with gcc 4.8.1 does not build code causing seg fault.

Am I triggering some undefined behavior, or really compiler bug is reason of such behavior?

Affected compiler:

gcc --version gcc.exe (tdm-1) 4.7.1

g++ --version g++.exe (tdm-1) 4.7.1

ld --version GNU ld (GNU Binutils) 2.22

Community
  • 1
  • 1
kwesolowski
  • 695
  • 8
  • 18

1 Answers1

2

This appears to be gcc bug 55893 that was fixed in 4.7.3. The attached testcase is very similar to yours:

struct foo
{
  virtual ~foo () { }
};

int main ()
{
  static const foo tmp;
}

The error occurs because gcc places the const object in read-only memory, because it is trivially constructible, without checking that the object has a non-trivial destructor. The destructor, being virtual, attempts to update the vtable pointer, leading to the segfault.

Praetorian
  • 106,671
  • 19
  • 240
  • 328