2

After compiling the source to .o files and using "ar rcs libMyLibrarylib.a *.o" to make the library I am getting segfaults because I am using a header file with the member variables and private functions striped out. When I use the exact same header I do not get the faults. The segfaults happen when deleting the pointers in the map.

header used to create the lib

#include <**Type**>
class A
{
   public:
    A();
    ~A(); //In the destructor I iterate through the map to free everything before
    void function();
   private:
    void privateFunction();
    std::map<**Type**, int*> myMap;
}

header used with the compiled library

class A
{
   public:
    A();
    ~A();
    void function();
}

Is there slicing or something when not using the exact header file? I want to hide the #include of Type from whomever is using the lib.

I have unit tests for the library, it does not segfault but it uses the same header file as was used to compile it.

Community
  • 1
  • 1
eliteslayer
  • 190
  • 6

2 Answers2

6

That's an illformed program, and you're running into undefined behavior. A class definition must be exactly the same across translation units in a program - as per 3.2 One definition rule [basic.def.odr] \6.

To hide the include of Type, you can just use the PIMPL idiom and not resort to these types of hacks.

class AImpl;
class A
{
   public:
    A();
    ~A(); //In the destructor I iterate through the map to free everything before
    void function();
   private:
    AImpl* pImpl;
}

You just move all logic and data members inside AImpl and keep the public interface as clean as possible. And all you need is a forward declaration of AImpl.

Luchian Grigore
  • 253,575
  • 64
  • 457
  • 625
1

In the client code your object has a different size. This will overwrite memory when the object is allocated in the stack or in the heap.

Emanuele Paolini
  • 9,912
  • 3
  • 38
  • 64