Alex Rivera | Logout

sprintf function's buffer overflow?

Asked 2010-11-26T03:11:41.377
17
{     
    char buf[8];
    sprintf(buf,"AAAA%3s","XXXXXXXX");
    printf("%s\n",buf);
}

What will happen?

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

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

Edit
Report

1 Answer

8

Instead of using this method you should try using the snprintf() method as described here. This method performs essentially the same function but it allows you to control the number of characters explictly, preventing undefined behaviour (this is a good thing)

snprintf is guaranteed not to write more than size bytes into str, so use of it can help avoid the risk of a buffer overflow Wiki

answered 2010-11-26T03:19:16.770

Your Answer