For C++ classes of any type, the class destructor fails to be called under the
following circumstances in the CYGWIN environment (not a problem in linux):

1) A static object of a class is declared within the body of a function which
is part of a shared library.

2) The shared library is loaded with dlopen, the function in question is
called, then the shared library is unloaded with dlclose.


Sample code:

// ---------------------------------

// File mymain.C

// ---------------------------------


#include <dlfcn.h>

using namespace std;

#include <iostream>


extern "C" void printit();

int main()
{
    void * LibraryHandle = dlopen("./mylib.sl", RTLD_LAZY);

    if(LibraryHandle)
    {
        void (*Printit)() = ( void (*)() )dlsym(LibraryHandle, "printit");
        (*Printit)();

        cout<<"Close library"<<endl;

        dlclose(LibraryHandle);

        cout<<"Library closed"<<endl;
    }
    else
        cout << dlerror() << endl;
}


// ---------------------------------

// File mylib.C

// ---------------------------------


using namespace std;

#include <iostream>

extern "C" void printit();

class KStr
{
  public:

     KStr(const char*);
    ~KStr();

     char StrBuf[20];
};

KStr::KStr(const char*Str)
{
    strcpy(StrBuf, Str);
}

KStr::~KStr()
{
  cout<<StrBuf<<endl;
}



 static KStr MyString1("Hello1");


void printit()
{
    static KStr MyString2("Hello2");
}



// ------------------------------------------
// Build script in cygwin
// ------------------------------------------

g++ mymain.C -o mymain
g++ mylib.C -shared -o mylib.sl


// ------------------------------------------
// Build script in linux
// ------------------------------------------

g++ mymain.C -o mymain -ldl
g++ mylib.C -shared -o mylib.sl



// When running the program in linux the normal output looks as follows:

Close library
Hello2
Hello1
Library closed


// When running the program in cygwin the output is as follows:

Close library
Hello1
Library closed
Segmentation fault (core dumped)



In cygwin the class destructor for "Hello2" is not called until the program is
exiting, after the shared library has been unloaded.  At that point the memory
for that particular class instance has apparently already been freed by the
dlclose operation resulting in a crash when the destructor is called.


I don't know if this is a gcc problem or a cygwin dlclose problem.

Harry Dellicker


-- 
           Summary: C++ class object destructors are not called for static
                    class objects in a shared library when dlclose is
                    called.
           Product: gcc
           Version: 3.4.4
            Status: UNCONFIRMED
          Severity: major
          Priority: P3
         Component: c++
        AssignedTo: unassigned at gcc dot gnu dot org
        ReportedBy: hbd_bugreports at earthlink dot net


http://gcc.gnu.org/bugzilla/show_bug.cgi?id=27319

Reply via email to