Disadvantages of scanf

前端 未结 9 1269
傲寒
傲寒 2020-11-22 00:34

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

9条回答
  •  谎友^
    谎友^ (楼主)
    2020-11-22 00:50

    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.

提交回复
热议问题