Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p><code>t</code> is pointing to a <em>string literal</em> it is undefined behavior to modify a <em>string literal</em>. The C++ draft standard section <code>2.14.5</code> <em>String literals</em> paragraph <em>12</em> says(<em>emphasis mine</em>):</p> <blockquote> <p>Whether all string literals are distinct (that is, are stored in nonoverlapping objects) is implementation defined. <strong>The effect of attempting to modify a string literal is undefined</strong>.</p> </blockquote> <p>The relevant section from the C99 draft standard is <code>6.4.5</code> <em>String literals</em> paragraph <em>6</em> which says(<em>emphasis mine</em>):</p> <blockquote> <p>It is unspecified whether these arrays are distinct provided their elements have the appropriate values. <strong>If the program attempts to modify such an array, the behavior is undefined.</strong></p> </blockquote> <p>On a typical modern Unix platform you will find <em>string literals</em> in the read-only segment which would result in a access violation if we attempt to modify it. We can use <em>objdump</em> to inspect the read-only section as follows:</p> <pre><code>objdump -s -j .rodata </code></pre> <p>we can see in the following <a href="http://coliru.stacked-crooked.com/a/95f61a4fe4a19155" rel="nofollow">live example</a> that the string literal will indeed be found in the <em>read-only</em> section. Note that I had to add a <code>printf</code> otherwise the compiler would optimize out the string literal. Sample `<em>objdump</em> output:</p> <pre><code>Contents of section .rodata: 400668 01000200 776f726c 64002573 0a00 ....world.%s.. </code></pre> <p>An alternative approach would be to have <code>t</code> point to an array with a copy of a <em>string literal</em> like so:</p> <pre><code>char r[] = "world"; char *const t = r ; </code></pre>
 

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