Note that there are some explanatory texts on larger screens.

plurals
  1. POPrevent leak after Ctrl+C when using read and malloc in a loop
    primarykey
    data
    text
    <p>I have to do a project, creating a shell in C. There will be a while loop waiting for characters to read in input.</p> <p>I think it's better to store characters we read in a pointer using <code>malloc</code> than in a buffer (array of characters) with fixed sized because we don't know how many characters will be sent. This way, I could use <code>realloc</code> on the pointer to get a larger size if needed.</p> <p>I've noticed with valgrind that when the program has finished reading characters and is waiting for new ones; if I press Ctrl+C, there will be memory leak. The only solution I've found to prevent this is to free the pointer after each command sent.</p> <p>Is this a good idea or is there a better way to do this? For information, I'm reading characters in a buffer buf and then concatenating string to the pointer str. Here is the code:</p> <pre><code>#include &lt;unistd.h&gt; #include &lt;stdlib.h&gt; #include &lt;string.h&gt; #include &lt;stdio.h&gt; #define READ_SIZE 1024 int main() { char buf[READ_SIZE]; char *str; int ret; int size; int max; str = NULL; size = 0; max = READ_SIZE; write(1, "$&gt; ", 3); while((ret = read(0, buf, READ_SIZE))) { if (str == NULL) { if ((str = malloc(READ_SIZE + 1)) == NULL) return EXIT_FAILURE; strncpy(str, buf, ret); str[ret] = '\0'; } else str = strncat(str, buf, ret); if (strncmp(&amp;buf[ret - 1], "\n", 1) == 0) { str[size + ret - 1] = '\0'; printf("%s\n", str); size = 0; max = READ_SIZE; free(str); str = NULL; write(1, "$&gt; ", 3); } else if (size + ret == max) { max *= 2; size += READ_SIZE; if ((str = realloc(str, max + 1)) == NULL) return EXIT_FAILURE; } else size += READ_SIZE; } free(str); return EXIT_SUCCESS; } </code></pre>
    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.
 

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