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.
scanfhere but rathergetc.scanf_s()or any of the other*_s()functions from Annex K of the C standard. They're no more secure than standard C functions if the standard ones are used properly, and the*_s()functions are not portable as implemented by Microsoft: "As a result of the numerous deviations from the specification the Microsoft implementation cannot be considered conforming or portable."