c++ - destruction of object with vector member -
c++ - destruction of object with vector member -
i encountered weird bug when coding classes vector member. bug introduced myself runtime result shocked me. simplified illustration shown below.
basically bug in constructor h2
has size of dimension_
rather dimension_*dimension_
, leads out-of-range access of h2
in void a::set()
, double a::get()
. admit it's bad have such kind of bug. think should happen h[2]
, h[3]
in void a::set()
access random memory address or in reserved range of vector h2
. has happened when destructor called free()
error raised, follow lot of dummy backtrace rather not list here.
*** glibc detected *** ./a.out: free(): invalid next size (fast): 0x0000000001637040 ***
but if don't access h[3]
in void a::set()
, won't happen. question happening vector , destructor? vector's destructor know elements have accessed? think vector knows size , deallocate memory when destructor called. thought appreciated. thanks.
the next sample code manifests runtime error.
#include<vector> #include<cstddef> #include<iostream> class { public: a(size_t dimension); virtual ~a(); public: virtual double get(); virtual void set(); protected: const size_t dimension_; std::vector<double> h1, h2; }; a::a(size_t dimension): dimension_(dimension), h1(dimension_*dimension_), h2(dimension) {} a::~a() { } double a::get() { set(); double result(0), temp(0); for(size_t i(0); < dimension_; ++i) { temp = 0; for(size_t j(0); j < dimension_; ++j) { temp += h1[j] * h2[j + i*dimension_]; } result += temp * h1[i]; } homecoming result; } void a::set() { h1[0] = h1[1] = h1[2] = h1[3] = 0.5; h2[0] = h2[1] = h2[2] = h2[3] = 0.005; } int main() { mya(2); std::cout << mya.get() << "\n"; homecoming 0; }
calling vector's operator[]
out-of-range argument results in undefined behavior (ub) technically anything @ might happen, including happening in case. 1 time invoke ub bets off; cannot reason ahead of time effects of code invokes ub.
note at()
method bounds checking , throw exception if effort access out-of-bounds element. if access out of bounds element exception right @ moment, makes debugging easier. downside bounds checks take bit of time, , if doing millions of vector accesses may notice at()
bit slower operator[]
. whether or not trade-off worth you.
having said that, happening clobbering book-keeping structures used c++ implementation's heap allocator. heap allocators typically allocate bit more memory requested, , utilize space store info allocation itself.
when vector goes free allocation used hold elements in vector, allocator finds book-keeping info has been destroyed, , wind assert.
c++ vector free destructor
Comments
Post a Comment