Problem Precondition:
- Program linked with 2 shared library, "libSub1.so" and "libSub2.so"
- Each shared library defines a global object with same name, "object"
- Such object has memory allocation in its construction and deletion in its destruction
Phenomenon:
Compile -> no error reportLink -> no error reportRun -> good, except a "double delete" error occurred after program run
Reproduce:
1. code (4 files)program.cchas nothing to do with the global object
#include <iostream> using namespace std; main(){ cout << "Hello World" << endl; }
sub1.cc
defines a global object
#include "object.h" Object object;
sub2.cc
defines a global object with the same name as the one in sub1
#include "object.h" Object object;
object.h
defines the object, who has the memory allocation in construction and memory deletion in destruction
#ifndef _OBJ_H_ #define _OBJ_H_ class Object{ public: Object(); ~Object(); private: char * buffer; }; #endif
object.cc
implements the object
#include "object.h" Object::Object(){ buffer = new char[10]; } Object::~Object(){ delete [] buffer; }
2.link(4 steps)
g++ object.cc -g -fPIC -shared -o libobject.sog++ sub1.cc -g -fPIC -shared -o libsub1.sog++ sub2.cc -g -fPIC -shared -o libsub2.sog++ -Wl,-rpath,. program.cc -L. -lsub1 -lsub2 -lobject -o test
3. run
./test
4. result
>./test
Hello World
*** glibc detected *** ./test: double free or corruption (fasttop): 0x09f6b018 ***