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?
I personally use the malloc approach, but you need to mind one more thing, you can also then limit the characters accepted with %s in the scanf to match your buffer.
You can then reallocate the memory after getting the string size by using the string function strlen and then adding 1 for the terminator.