Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>This is pretty simple, but very surprising if you're used to a higher-level language. <em>C does not manage memory for you</em>, and <em>C doesn't really have strings</em>. That <code>content</code> variable is a pointer, not a string. You have to manually allocate the space you need for the string before calling <code>strcat</code>. The correct way to write this code is something like this:</p> <pre><code>FILE *fp = fopen(filename, "r"); if (!fp) { syslog(LOG_INFO, "failed to open %s: %s", filename, strerror(errno)); return xstrdup("&lt;!DOCTYPE html&gt;&lt;html lang=\"en-US\"&gt;&lt;head&gt;&lt;title&gt;Test&lt;/title&gt;" "&lt;/head&gt;&lt;body&gt;&lt;h1&gt;Does Work&lt;/h1&gt;&lt;/body&gt;&lt;/html&gt;"); } else { size_t capacity = 4096, offset = 0, n; char *content = xmalloc(capacity); size_t n; while ((n = fread(content + offset, 1, capacity - offset, fp)) &gt; 0) { offset += n; if (offset == capacity) { capacity *= 2; content = xrealloc(content, capacity); } } if (n &lt; 0) syslog(LOG_INFO, "read error from %s: %s", filename, strerror(errno)); content[offset] = '\0'; fclose(fp); return content; } </code></pre> <p>Notes:</p> <ol> <li>Error messages triggered by I/O failures should ALWAYS include <code>strerror(errno)</code>.</li> <li><code>xmalloc</code>, <code>xrealloc</code>, and <code>xstrdup</code> are wrapper functions around their counterparts with no leading <code>x</code>; they crash the program rather than return <code>NULL</code>. This is almost always less grief than trying to recover from out-of-memory by hand in every single place where it can happen.</li> <li>I return <code>xstrdup("...")</code> rather than <code>"..."</code> in the failed-to-open case so that the caller can always call <code>free(content)</code>. Calling <code>free</code> on a string literal will crash your program.</li> <li>Gosh, that was a lot of work, wasn't it? This is why people tend to prefer to write web apps in a higher-level language. ;-)</li> </ol>
 

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