Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>In the case where <code>p="hello world";</code> (1st case at the time of this edit), <code>p</code> is being initialized to point to a <em>read-only</em> memory region which contains the string "hello world" (string literal). This <em>read-only</em> memory region is created at compile time.</p> <p>In the case that causes the segmentation fault (2nd case at the time of this edit), <code>p</code> is uninitialized and copying anything to it will produce unpredictable results because the location in memory that <code>p</code> is pointing to is not specified by the code.</p> <p>Before you can copy a string to <code>p</code>, you must specify the memory that <code>p</code> is pointing to. </p> <p>You can allocate this memory on the stack </p> <p><code>char buf[BUFSIZ] = ""; /* local variable */</code></p> <p>on the heap</p> <p><code>char *buf = malloc(BUFSIZ); /* don't forget to free */</code></p> <p>or in the __DATA segment.</p> <p><code>static char buf[BUFSIZ] = ""; /* global variable */</code></p> <p>You can then initialize <code>p</code> to point at the memory buffer.</p> <p><code>char *p = buf;</code></p> <p>This is similar in concept to initializing <code>p</code> to point to the string literal in <em>read-only</em> memory. Unlike the case where <code>p</code> points to the string literal, you can now copy a string to the character pointer as it does not point to <em>read-only</em> memory.</p> <p><strong>Note:</strong> I intentionally created a separate buffer and initialized <code>p</code> to point to it to help make my point.</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. 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