visual c++ - Copy Constructor for MyString causes HEAP error. Only Gives Error in Debug Mode -


so, i've never experienced before. when error, triggers breakpoint. however, time when build solution , run without debugging (ctrl+f5), gives me no error , runs correctly. when try debugging (f5), gives me error:

heap[mystring.exe]: heap: free heap block 294bd8 modified @ 294c00 after freed windows has triggered breakpoint in mystring.exe.  may due corruption of heap, indicates bug in mystring.exe or of dlls has loaded.  may due user pressing f12 while mystring.exe has focus.  output window may have more diagnostic information. 

this assignment due tonight, i'd appreciate quick help.

my code here: https://gist.github.com/anonymous/8d84b21be6d1f4bc18bf

i've narrowed problem down in main line 18 in main.cpp ( c = + b; ) concatenation succeeds, when copied c, error message occurs @ line 56 in mystring.cpp ( pdata = new char[length + 1]; ).

the kicker haven't had problem line of code until tried overloading operator>>. i've since scrapped code sake of trying debug this.

again, appreciated!

let's go through line 18:

 1. in line 17 create string c dynamically allocated memory inside. 2. make assignment: c = + b:   2.1. operator+ creates local object 'cat'.   2.2. cat's memory allocated dynamically.   2.3. cat becomes concatenation of 2 given strings.   2.4. operator+ exits. cat local object , it's being destroyed.     2.4.1. cat being destroyed. cat's destructor runs.     2.4.2. destructor deletes pdata;     2.4.3. after delete make *pdata = null. //error - should pdata = null (1)   2.5. c initialized result of operator+.   2.6. operator= calls copy().   2.7. copy() allocates new memory without checking current one. //error - memory leak (2) 

(1) pdata char*. in destructor have: delete[] pdata (deletes memory) , *pdata = null. because pdata pointer, *pdata same pdata[0]. write freed memory. cause of error.

(2) additional problem. copy() overwrites current memory without checking. should be:

copy() {     if(this->pdata)     {         delete this->pdata;     }     //now allocate new buffer , copy } 

also, when dealing raw bytes (chars), don't want use new() , delete(), malloc() , free() instead. in case, in functions copy(), instead of calling delete() , new(), use realloc().

edit: 1 more thing: errors caused heap damage occur during debugging. in release binary, overwrite freed (and maybe used else) memory. that's why debugging important when playing memory in c++.


Comments

Popular posts from this blog

c# - How Configure Devart dotConnect for SQLite Code First? -

java - Copying object fields -

c++ - Clear the memory after returning a vector in a function -