I want to get a string input from a user in C.
I know how to use scanf
to get string inputs. I know how to use malloc
and realloc
to allocate space for a variable.
The problem is when the user enters a string, I don't necessarily know what size that will be that I will need to reserve space for.
For instance if they write James
I'd need to malloc((sizeof(char) * 5)
but they might have written Bond
in which case I would have only had to malloc(sizeof(char) * 4)
.
Is it just the case that I should be sure to allocate enough space beforehand (e.g. malloc(sizeof(char) * 100)
).
And then does scanf
do any realloc
trimming under the hood or is that a memory leak for me to fix?
There are multiple approaches to this problem:
use an arbitrary maximum length, read the input into a local array and allocate memory based on actual input:
use non-standard library extensions, if supported and if allowed. For example the GNU libc has an
m
modifier for exactly this purpose:read input one byte at a time and reallocate the destination array on demand. Here is a simplistic approach: