Skip to content

Instantly share code, notes, and snippets.

@flux77
Last active September 15, 2019 15:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save flux77/9892a7dfb930935168059abe624aeae7 to your computer and use it in GitHub Desktop.
Save flux77/9892a7dfb930935168059abe624aeae7 to your computer and use it in GitHub Desktop.
/* Improved version for https://codereview.stackexchange.com/questions/228979/read-string-of-any-length-in-c */
#include <stdlib.h>
#include <stdio.h>
/* Reads string input up to, but not including, the first newline or EOF.
* Returns a pointer to the string, or NULL on error.
* The pointer to the string must be freed.
*/
char* input() {
size_t bufsize = 10; /* Initial buffer size. */
char *s = malloc(bufsize);
if (s == NULL) {
return NULL;
}
size_t s_len = 0; /* Current length of string excluding null character. */
int ch;
while((ch = getchar()) != '\n' && ch != EOF) {
s[s_len] = (char) ch;
s_len++;
if (s_len + 1 > bufsize) {
bufsize *= 2;
char *temp_buf = realloc(s, bufsize);
if (temp_buf == NULL) {
free(s);
return NULL;
}
s = temp_buf;
}
}
s[s_len] = '\0';
return s;
}
int main() {
printf("Name: ");
fflush(stdout);
char *s = input();
if (s == NULL) {
fprintf(stderr, "Error: input()\n");
exit(1);
}
printf("%s\n", s);
free(s);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment