Skip to content

Instantly share code, notes, and snippets.

@1995eaton
Created November 8, 2014 23:29
  • Star 5 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save 1995eaton/06ee2dfe7f83ce0d2e7d to your computer and use it in GitHub Desktop.
C stdin reader example with dynamic memory allocation
#include <stdio.h>
#include <stdlib.h>
static char *
read_stdin (void)
{
size_t cap = 4096, /* Initial capacity for the char buffer */
len = 0; /* Current offset of the buffer */
char *buffer = malloc(cap * sizeof (char));
int c;
/* Read char by char, breaking if we reach EOF or a newline */
while ((c = fgetc(stdin)) != '\n' && !feof(stdin))
{
buffer[len] = c;
/* When cap == len, we need to resize the buffer
* so that we don't overwrite any bytes
*/
if (++len == cap)
/* Make the output buffer twice its current size */
buffer = realloc(buffer, (cap *= 2) * sizeof (char));
}
/* Trim off any unused bytes from the buffer */
buffer = realloc(buffer, (len + 1) * sizeof (char));
/* Pad the last byte so we don't overread the buffer in the future */
buffer[len] = '\0';
return buffer;
}
int
main (void)
{
char *input = read_stdin();
printf("%s\n", input);
free(input); /* Don't forget to free the memory allocated with malloc */
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment