Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>It's because of:</p> <pre><code>String s("test"); </code></pre> <p>What this does is to pass the <code>const char *</code> <code>"test"</code> to your constructor which then simply stores the address of that string.</p> <p>Later, when you try to modify the memory that the pointer points to, that's undefined behaviour.</p> <p>Typically, string literals will be stored in read-only memory to allow certain optimisations to take place, and any attempt to modify them will result in a access violation.</p> <p>If you were to change:</p> <pre><code>String s("test"); </code></pre> <p>into:</p> <pre><code>char cp[] = "test"; String s(cp); </code></pre> <p>you may well find it will work.</p> <p>However, your class should really be making a <em>copy</em> of the string for its own purposes - a mere pointer is unsafe, since the code that passed you that pointer can change the contents of it as well.</p> <p>Things you should change in your code to make it safer:</p> <ul> <li><code>s</code> should be a private member, not a public one.</li> <li>your constructor should make its own copy of the string:<br><code>s = new char[strlen(x)+1];</code><br><code>strcpy (s,x);</code>.</li> <li>add a destructor to take care of that as well:<br><code>String::~String() { delete[] s; }</code>.</li> <li>consider having your constructor receive a <code>const char *</code> (since you're <em>not</em> changing it).</li> <li>consider using <code>toupper(ch)</code> instead of <code>ch - 'a' + 'A'</code>. While your formula works for ASCII, I don't believe it's guaranteed by the standard.</li> <li><code>cout</code> stuff should be handled by the class rather then code outside of it (this will be mandatory once you make <code>s</code> private.</li> <li>consider having a no-argument constructor so that string arrays will work okay.</li> </ul>
    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. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      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