sprintf buffer sizes

后端 未结 3 1863
無奈伤痛
無奈伤痛 2021-01-20 19:00

I\'m a novice programmer, but usually I can unravel my own issues. This time I solved the issue, but it still stumps me. A friend suggested I ask this community for input.

相关标签:
3条回答
  • 2021-01-20 19:38

    C strings are null terminated. If you have 2 characters ("10" for example) you need a buffer sized 2 + 1 for the null terminator.

    sprintf() adds this to the end of your buffer; in your current case you actually have a buffer overflow because you're not providing enough space.

    The modern, safer approach is to use snprintf() to which you supply the length of the buffer.

    0 讨论(0)
  • 2021-01-20 19:40

    I assume that sprintf adds a \0 at the end of the generated string. So for instance if you print the number 99, you'd get "99\0" in your buffer, so for a buffer with length 2, that causes problems.

    0 讨论(0)
  • 2021-01-20 19:55

    You're forgetting the NUL terminator. In C, strings require an extra character for the terminator, so char buf[2] ought to be char buf[3] to accommodate numbers between 10 and 99.

    Incidentally, your code demonstrates why sprintf is dangerous as it can write past the output buffer and enable stack smashing attacks. A better options is to use snprintf.

    0 讨论(0)
提交回复
热议问题