Alex Mancha
Alex Mancha

Reputation: 28

Why sprintf crash in this case?

I'm running the following function:

void f () {
    int n = 10;
    char *buffer = new char[n*2];

    for(int i = 0; i < n; i++) {

        sprintf(buffer + (i*2), "%.2X",i);
    }

    delete[] buffer;
}

and in some cases this function crash. Running valgrind, I can see the following problem:

==26747== Invalid write of size 1
==26747==    at 0x56CC2C9: vsprintf (in /usr/lib64/libc-2.17.so)
==26747==    by 0x56AE456: sprintf (in /usr/lib64/libc-2.17.so)

Can anyone explain what's happening?

Upvotes: 0

Views: 125

Answers (1)

bruno
bruno

Reputation: 32586

buffer is sized 20, but when i values 9 you do sprintf(buffer + 18, "%.2X",i); writting 3 characters because of the ending null character, and that null character is written at buffer + 20 which is out of buffer

you need char *buffer = new char[n*2 + 1];

Upvotes: 3

Related Questions