Blog
Gcc Pain
Date: 22/10/2008
It seems that gcc even in it's more recent versions (v4.2 in my case) has an obnoxious little bug in that 2 classes defined locally in separate C++ files can "intermingle" in the global namespace and cause chaos. e.g.
// File1.cpp
class ClassA
{
    int a;

public:
    ClassA()
    {
         a = 1;
    }

    ~ClassA()
    {
    }
};

void MethodA()
{
    ClassA instance1;
}
And...
// File2.cpp
class ClassA
{
    char *b;

public:
    ClassA()
    {
         b = strdup("Hello");
    }

    ~ClassA()
    {
         free(b);
    }
};

void MethodB()
{
    ClassA instance2;
}
In Visual C++ this is fine, the 2 classes have scope limited to their local C++ file and using them causes no issues.

However in gcc C++ destroying ClassA in one C++ file can result in the destructor from the "other" ClassA to be called, i.e. File1.cpp's trying to destroy the stack variable instance1 and ends up in File2.cpp's ClassA::~ClassA() implementation, which tries to free the string and crashes.

Awesome. And this goes on with no compile or link time errors or warnings. You just find out the hard way at runtime. And if the classes are similar enough you might not even notice the problem until later.

Very insidious indeed. Just beware.

This week I found 2 pairs of classes with the same name, one of which causes a crash, and the other I only noticed because of valgrind complained I was writing off the end of a block of memory. In both cases there was one original copy of the code and I made of a copy of it to implement a different version or mode of operation, each with a local helper class, with the same name. One was the old scripting engine vs the new one, and the other case was the Mail2 backend (Scribe v2) vs the Imap backend.

(Of course I could've missed something really basic with my makefile's or compile options, and I'm happy to take blame if it's me doing something dumb. But I think I'm doing fairly mundane and reasonable things in those areas so I doubt it's my fault in this case)
 
Reply
From:
Email (optional): (Will be HTML encoded to evade harvesting)
Message:
 
Remember username and/or email in a cookie.
Notify me of new posts in this thread via email.
BBcode:
[q]text[/q]
[url=link]description[/url]
[img]url_to_image[/img]
[pre]some_code[/pre]
[b]bold_text[/b]