Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Let's go through line 18:</p> <pre> 1. In line 17 you create string c with dynamically allocated memory inside. 2. You make assignment: c = a + b: 2.1. Operator+ creates LOCAL object 'cat'. 2.2. cat's memory is allocated dynamically. 2.3. cat becomes concatenation of two given strings. 2.4. Operator+ exits. cat is LOCAL object and it's being destroyed. 2.4.1. cat is being destroyed. cat's destructor runs. 2.4.2. destructor deletes pData; 2.4.3. After delete you make *pData = NULL. //ERROR - should be pData = NULL (1) 2.5. c is initialized with result of operator+. 2.6. operator= calls copy(). 2.7. copy() allocates new memory without checking the current one. //ERROR - memory leak (2) </pre> <p><strong>(1)</strong> pData is char*. In destructor we have: delete[] pData (deletes memory) and then *pData = NULL. Because pData is a pointer, *pData is same as pData[0]. So you write to already freed memory. This is the cause of your error.</p> <p><strong>(2)</strong> Additional problem. Copy() overwrites current memory without checking. Should be:</p> <pre><code>copy() { if(this-&gt;pData) { delete this-&gt;pData; } //now allocate new buffer and copy } </code></pre> <p>Also, when dealing with raw bytes (chars), you don't want to use new() and delete(), but malloc() and free() instead. In this case, in functions like copy(), instead of calling delete() and then new(), you would simply use realloc().</p> <p>EDIT: One more thing: errors caused by heap damage usually occur during debugging. In release binary, this will simply overwrite some freed (and maybe already used by someone else) memory. That's why debugging is so important when playing with memory in C++.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload