user3014282
user3014282

Reputation: 209

sprintf in C, loop never ends

I am having a problem with loop, I don't know why but loop never ends.

int main(int argc, char *argv[])
{
    int j;
    char s[2];
    for(j=1;j<=3;j++)
    {
        sprintf(s,"s%d",j);
        printf("%s", s);
    }
    system("PAUSE");    
    return 0;
}

I think loop should show s1s2s3 in console.

Upvotes: 5

Views: 1805

Answers (2)

user1508519
user1508519

Reputation:

char s[2]; should be char s[3];, or else you will get a buffer overflow.


Abhineet explains why the change is necessary. However, in order to corroborate his answer, here is the relevant section from the standard.

7.19.6.6

The sprintf function is equivalent to fprintf, except that the output is written into an array (specified by the argument s) rather than to a stream. A null character is written at the end of the characters written; it is not counted as part of the returned value. If copying takes place between objects that overlap, the behavior is undefined.

Upvotes: 8

Abhineet
Abhineet

Reputation: 5399

From the documentation,

The size of the buffer should be large enough to contain the entire resulting string.

You are already pushing two chars to s, so, there is not enough space for appending \0. This will cause undefined behavior. The solution is to provide one extra char memory to append \0.

char s[2]; to char s[3];

I know I have replied pretty late but couldn't stop myself from explaining the OP, "why he has to use s[3] instead of s[2] ?"

Upvotes: 4

Related Questions