c++ - Setting class member to null in destructor -
in this page there's piece of code:
class mystring { private: char *m_pchstring; int m_nlength; public: mystring(const char *pchstring="") { // find length of string // plus 1 character terminator m_nlength = strlen(pchstring) + 1; // allocate buffer equal length m_pchstring = new char[m_nlength]; // copy parameter our internal buffer strncpy(m_pchstring, pchstring, m_nlength); // make sure string terminated m_pchstring[m_nlength-1] = '\0'; } ~mystring() // destructor { // need deallocate our buffer delete[] m_pchstring; // set m_pchstring null in case m_pchstring = 0; } char* getstring() { return m_pchstring; } int getlength() { return m_nlength; } };
in destructor, writer sets m_pchstring null , says in case. can happen if don't set null? have deallocated specified memory , class members killed upon exit. benefit of doing so?
if pointer set null
, bug deleted object used, example through dangling pointer object, might hidden because buggy code may check null
before trying use data. in 1 way of thinking might consider 'safe' behavior, what's happening you're hiding defect has occurred.
keep in mind hiding bugs not same fixing bugs. dangling pointer might used again after memory has been reallocated, valid pointer placed same memory location. @ point buggy code start using new, valid pointer, incorrect reasons.
so might better set pointer cause crash if it's improperly used:
m_pchstring = (char*) 0xdeaddead;
now if tries use member pointer of deleted object (which bug), it'll fast fail , bug caught rather hidden.
in debug builds msvc (and possibly other toolchains) you'll behavior debug heap. msvc debug heap fills memory freed via free()
or operator delete
value 0xdd: https://stackoverflow.com/a/370362/12711
Comments
Post a Comment