sprintf function's buffer overflow?

2019-02-12 16:45发布

{     
    char buf[8];
    sprintf(buf,"AAAA%3s","XXXXXXXX");
    printf("%s\n",buf);
}

what will happen?

The buffer have 8 characters space and only 3 free characters left, however, "XXXXXXXX" is 8 characters long.

I take a test with Visual Studion 2008 on Windows 7. As a result, the program printed:AAAXXXXXXX, and a run-time error happened.

7条回答
爱情/是我丢掉的垃圾
2楼-- · 2019-02-12 17:47

You have a bug/typo in your format string. Instead of "AAAA%3s" it should be "AAAA%.3s". Field [minimum] width and field precision are very different. The former sets the minimum number of bytes the field will expand to fill. The latter (for strings) sets the maximum number of bytes that will be output; additional bytes of the string are neither inspected nor copied to the output.

查看更多
登录 后发表回答