Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Here are the issues that I found:</p> <ul> <li>You cannot call <code>fflush()</code> on <code>stdin</code>. It leads to undefined behavior. <code>fflush()</code> is only for output streams.</li> <li>The type for <code>c</code> should be an <code>int</code>. The <code>getchar()</code> will return <code>EOF</code> when there is no more input, and <code>EOF</code> is a value not equal to any valid value for <code>unsigned char</code>. That is why <code>getchar()</code> returns an <code>int</code>, so your variable receiving the return value of <code>getchar()</code> should match that type.</li> <li>The sense of the <code>while</code> check is incorrect. You will only leave the loop if <code>c</code> equals both <code>\n</code> and <code>\0</code> at the same time, which is not possible. Thus the loop will never exit. If you actually ended the input given to your program, you probably entered an infinite loop, continually allocating until your system ran out of memory. So, you want to leave the loop if <code>c</code> equals <code>\n</code> or <code>\0</code>.</li> <li>You should add a check to leave the loop if <code>c</code> is <code>EOF</code>.</li> <li>You should make sure <code>num_read</code> is less than <code>buffer_size</code> before you assign the <code>\0</code> character. This can be done by moving your <code>realloc()</code> code to be at the bottom of the <code>while</code> loop instead of at the top.</li> </ul> <p>With these changes, the code looks like:</p> <pre><code>char *user_input() { char *buffer = NULL; size_t num_read = 0; size_t buffer_size = 100; int c = '\0'; char *new_buffer = NULL; buffer = malloc(buffer_size); c = getchar(); while (!(c == EOF || c == '\n' || c == '\0')) { assert(num_read &lt; buffer_size); buffer[num_read++] = c; if (num_read &gt;= buffer_size) { buffer_size *= 2; // try a buffer that's twice as big as before new_buffer = realloc(buffer, buffer_size); if (new_buffer == NULL) { free(buffer); return NULL; } buffer = new_buffer; } c = getchar(); } //while assert(num_read &lt; buffer_size); buffer[num_read] = '\0'; return buffer; } </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