i seem have issue dynamic memory allocation.
below you'll see derived class contains pointer name variable dynamically allocated using void name(const char* name)
method. function run product constructor, sets name product class when object created. here's class:
namespace sict { class product :public streamable { char* name_; public: product(const char* name); virtual ~product(); void name(const char* name); }
and here's name function itself, along 1 argument constructor:
void sict::product::name(const char * name) { int g = strlen(name); name_ = new char[g]; strncpy(name_, name, g); name_[g] = 0; } product::~product() { delete [] name_; name_ = nullptr; }
to me code seems capable enough of created object destroying peacefully whenever exits scope of function it's running in. however, when function ends , destructor runs, program freezes/crashes @ delete [] name_
. running program on visual studio's compiler seems yield no particular errors (other program freezing), gcc compiler detects sort of heap corruption. know why happening?
i'm not sure why sean cline didn't post comment answer, sean correct.
name_
given g
elements , name_[g]
set zero, name_[g]
1 past end of array. either use name_ = new char[g+1];
or name_[g-1] = 0;
don't go past end of array.
also, several comments point out, time have class allocates memory dynamically, make sure define copy constructor, assignment operator, , destructor. if miss one, default implementation perform shallow copy, can cause headaches you.
a shallow copy when pointer copied instead of data points to. in case, if object of class ever copied or assigned, end 2 objects pointing same data on heap, , both try delete when run destructors.
for more information on functions, see rule of 3
Comments
Post a Comment