Note that there are some explanatory texts on larger screens.

plurals
  1. POWhat does new [size_t] + 1 return
    primarykey
    data
    text
    <p>The following sample of code if from a book "C++ von A bis Z" (second edition, translation: C++ from A to Z) at page 364. The sample is wrong.</p> <pre><code>// overload operator += #include &lt;iostream&gt; #include &lt;cstring&gt; using namespace std; class String { private: char* buffer; unsigned int len; public: String(const char* s="") { // cout &lt;&lt; "Constructor: " &lt;&lt; s &lt;&lt; "\n"; len = strlen(s); buffer = new char [len+1]; strcpy(buffer, s); } ~String() { // cout &lt;&lt; "Destructor: " &lt;&lt; buffer &lt;&lt; "\n"; delete [] buffer; } String(const String&amp; s) { // cout &lt;&lt; "Copy_Constructor: " &lt;&lt; s.get_buffer() &lt;&lt; "\n"; len = s.len; buffer = new char [len+1]; strcpy(buffer, s.buffer); } char* get_buffer() const { return buffer; } // returning a reference is more efficent // String&amp; operater+=(const String&amp; str1) String operator+=(const String&amp; str1) { // cout &lt;&lt; "Assignment_Operator +=: " &lt;&lt; str1.get_buffer() &lt;&lt; "\n"; String tmp(*this); delete [] buffer; len = tmp.len + str1.len; // invalid pointer // buffer = new char[len+1]; buffer = new char [len]+1; strcpy(buffer, tmp.buffer); strcat(buffer, str1.buffer); // wrong return_type // return *this; return buffer; } }; int main(void) { String string1("Adam"); String string2("Eva"); string1+=" und "; string1.operator+=(string2); cout &lt;&lt; string1.get_buffer() &lt;&lt; "\n"; return 0; } </code></pre> <p>The lines with the comments are my "fixes". Now I want to know what "new char [len]+1" does? I think the following:</p> <ul> <li>it allocates sizeof(char)*len memory from heap</li> <li>and returns the WRONG address to the pointer *buffer</li> <li>but what is the wrong address: "first address of the new memory on heap + 1" or "first address of the new memory on heap + sizeof(char)*1)?</li> </ul> <p>What happens? Thanks</p> <p>// edit Thank you all! You helped me! I just wanted to know, what this statement will return.</p> <pre><code>new char [len]+1; </code></pre> <p>The line itself is, of course, a typo from the author of the book.</p>
    singulars
    1. This table or related slice is empty.
    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.
 

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