segmentation fault - C++ deque throwing Segfaults -
i have code project doesn't seem working.
i trying make deque (of struct) static member of class. skeleton/basic code follows (i have retained datatypes - my_typedef_fn data type got typedef-ing function pointer) :
1.h file :
class { struct bstruct { char * b_name; my_typedef_fn b_func; } static std::deque<bstruct> a_deque; static void func(); }
1.cpp file :
std::deque<a::bstruct> a::a_deque; void a::func(char * name, my_typedef_fn fn) { a_deque.push_front((bstruct) {name, fn} ); // <<<< segfault ! }
from understanding - .h file declares stuff (as usual) - first line in .cpp initializes static member a_deque - function func adds stuff deque using push_back
but segmentation error @ line push_front called (found using gdb).
also, when print a_deque.size() before push_front 4294967264 before segfault , when count number of elements in deque using loop :
int counter = 0 for( std::deque<bstruct> = a_deque.begin(); != a_deque.end(); it++, counter++ );
my counter shows 0 elements in
so, not understand why segfault nor why .size() large garbage number
-- edit 1 -- adding way functions called :
2.cpp
#include "1.h" void fn1() { // code } a::func("abc", fn1);
it complied commands :
g++ -c -w -fpermissive -o 1.o 1.cpp g++ -c -w -fpermissive -o 2.o 2.cpp g++ -o final 1.o 2.o
it not possible call function in global scope, you're showing in 2.cpp
. mentioned code old, maybe it's pre-standard thing, or extension.
anyway, you've shown function being called in 2.cpp
, while static data member a_deque
defined in 1.cpp
. means you're falling prey static initialisation order fiasco. globals (such static data members, , apparently weird free-standing function call well) initialised/executed in order appear within 1 translation unit (= .cpp
file), order across translation units unspecified.
which means it's possible a::func()
access a_deque
before constructor of a_deque
has run, possibly lead segfault (as internal data members of deque have 0 or possibly random values).
to fix this, you'll have rid of situation somehow. 1 option move global code can access a_deque
1.cpp
, place after definition of a_deque
.
an alternative replace a_deque
function-scope static variable, guaranteed initialised before first use:
1.h
class { struct bstruct { char * b_name; my_typedef_fn b_func; } static std::deque<bstruct>& a_deque(); static void func(); }
1.cpp
#include "1.h" std::deque<a::bstruct>& a::a_deque() { static std::deque<bstruct> d; return d; } void a::func(char * name, my_typedef_fn fn) { a_deque().push_front((bstruct) {name, fn} ); // <<<< no more segfault }
Comments
Post a Comment