c++ class library dynamic runtime allocation -


suppose i' have interface class

class foo_if_t {  }; 

, first library libfoo_orig.so class foo_t inherits foo_if_t , has following code:

#include "foo_if.h"  class foo_t : public foo_if_t{ private:     int res; public:     foo_t(){}     virtual ~foo_t(){} }; 

and second library libfoo_mod.so class foo_t redefined follows:

#include "foo_if.h"  class foo_t : public foo_if_t{ private:     int res[100]; public:     foo_t() {          (int i=0; i<100; i++)          res[i] = i;     }     virtual ~foo_t(){} }; 

i create symlink libfoo.so --> libfoo_orig.so , compile following application

#include "foo_orig.h"  int main(){     foo_if_t *foo_if = new foo_t();     delete foo_if; } 

with g++ -ggdb -o0 test.cpp -o test -l. -lfoo (hence linking libfoo.so).

at point change symlink target libfoo_mod.so , rerun code. result in following error:

*** error in `./test': free(): invalid next size (fast): 0x0000000001ec9010 *** aborted (core dumped) 

what believe happening constructor allocation of foo_t library foo_orig.so eats smaller chunk of heap 1 foo_mod.so, when foo_mod.so foo_t constructor invoked, dirties heap memory beyond allocation boundaries (hence corrupting heap next chunk reference). telling me heap reservation somehow pre-calculated @ link time, whereas thought resolved dynamically @ runtime, based on actual constructor code invoked. getting wrong, and, if not, why produced output code behaving ?

as counter-proof test, i've wrapped new foo_t() invocation within implementation of static foo_it_t * foo_if_t::new_instance() written each library; invoking new_instance main code works right.

the problem here library code , main program code have different idea of layout structure of foo_t. though both recognise existence of type, have both been compiled different version of header defines it. going lead big trouble.

in case, trouble caused fact actual memory allocation, performed new, compiled main program , has 1 idea of size of created object is. constructor meanwhile, compiled library code , has entirely different idea of underlying object size. main program creates object on heap sizeof(foo_t) - sizeof(int) point of view. constructor, not knowing this, happily trounces memory 100 ints, corrupting heap.

basically cannot 'cheat' in way. if change header files should recompile libraries depend on header, or face unpredictable trouble (obviously you're doing intentionally in case, can done accident too).


Comments

Popular posts from this blog

javascript - Laravel datatable invalid JSON response -

java - Exception in thread "main" org.springframework.context.ApplicationContextException: Unable to start embedded container; -

sql server 2008 - My Sql Code Get An Error Of Msg 245, Level 16, State 1, Line 1 Conversion failed when converting the varchar value '8:45 AM' to data type int -