Friday, 15 March 2013

c - Why does the following contain only str-3 -



c - Why does the following contain only str-3 -

the output of next "str-3," expect "str-2,str-3,"

if alter snprintf sprintf works how expected to; shouldn't snprintf , sprintf behave same?

int main (int argc, char **argv) { char str[64]; str[0] = '\0'; snprintf(str, 64, "%s%s,", str, "str-2"); snprintf(str, 64, "%s%s,", str, "str-3"); printf("%s\n",str); }

the description of snprintf in c standard (c99, 7.19.6.5) says:

if copying takes place between objects overlap, behavior undefined.

this happens here since str used both input , output.

the same restriction applies sprintf. fact happened work accident, can happen undefined behavior.

c

No comments:

Post a Comment