I want to know the disadvantages of scanf()
.
In many sites, I have read that using scanf
might cause buffer overflows. What is the reason f
Many answers here discuss the potential overflow issues of using scanf("%s", buf)
, but the latest POSIX specification more-or-less resolves this issue by providing an m
assignment-allocation character that can be used in format specifiers for c
, s
, and [
formats. This will allow scanf
to allocate as much memory as necessary with malloc
(so it must be freed later with free
).
An example of its use:
char *buf;
scanf("%ms", &buf); // with 'm', scanf expects a pointer to pointer to char.
// use buf
free(buf);
See here. Disadvantages to this approach is that it is a relatively recent addition to the POSIX specification and it is not specified in the C specification at all, so it remains rather unportable for now.