How to input a string with unknown size

  • A+

I'm a bit confused about strings in C. I understand that declaring buffer size is important since otherwise, it can cause buffer overflow. But I need to know how do I take a string input that I don't know the size of. For instance, if I wanted to take a line of text from the user as input and I had no way of knowing how long their text would be, how do I do it?

I've tried dynamically allocating memory as the user gives an input. Here's the code-

#include<stdio.h> #include<stdlib.h>  int main() {     char *str, ch;     int size = 10, len = 0;     str = realloc(NULL, sizeof(char)*size);     if (!str)return str;     while (EOF != scanf_s("%c", &ch) && ch != '/n')     {         str[len++] = ch;         if (len == size)         {             str = realloc(str, sizeof(char)*(size += 10));             if (!str)return str;         }     }     str[len] = '/0';     printf("%s/n", str);     free(str); } 

The problem is, when I compile it using VS-2017, I get these errors-

source.c(10): warning C4473: 'scanf_s' : not enough arguments passed for format string

source.c(10): note: placeholders and their parameters expect 2 variadic arguments, but 1 were provided

source.c(10): note: the missing variadic argument 2 is required by format string '%c'

source.c(10): note: this argument is used as a buffer size

I think that dynamically allocating memory as I go on(like in the above code) should work, but I'm probably doing something wrong. Is there a way to make this work?

EDIT: Word.


  1. You should use getchar not scanf_s
  2. You should use int ch; not char ch; for EOF

The following code could work:

#include<stdio.h> #include<stdlib.h>  int main() {     char *str = NULL;     int ch;     size_t size = 0, len = 0;      while ((ch=getchar()) != EOF && ch != '/n') {         if (len + 1 >= size)         {             size = size * 2 + 1;             str = realloc(str, sizeof(char)*size);         }         str[len++] = ch;     }     if (str != NULL) {         str[len] = '/0';         printf("%s/n", str);         free(str);     }      return 0; } 


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: