简体   繁体   中英

C, Malformed int to char[] after strcat

When printing a char[] that has the value of an int concat'ed into it, the int is not correct. However the printf of str after the sprintf outputs the correct value.

I'm using this code:

  int i;
  for( i = 0; i < 10; i++){
        char str[20];
        sprintf(str, "%i", i);
        char in[50] = "INSERT INTO `Test` (`Col1`, `Col2`) VALUES ('1', '";
        strcat(in, str);
        strcat(in, "')");
        printf("%s", in);
   }

Output: INSERT INTO Test (Col1, Col2) VALUES ('1', 'A&?0')

in is too small as the string literal is 50 characters, meaning the strcat() afterwards are writing beyond the end of the buffer causing undefined behaviour, in this case causing corruption (in fact the string literal is 50 + 1 due to the implicit null terminator appended to string literals). To correct increase the size of the buffer and use snprintf() to prevent buffer overrun and to perform the string construction in a single operation. For example:

for (int i = 0; i < 10; i++)
{
    char str[128];

    const int result =
        snprintf(str,
                 sizeof(str),
                 "INSERT INTO `Test` (`Col1`, `Col2`) VALUES ('1', '%i')",
                 i);

    if (-1 == result)
    {
        fprintf(stderr, "Failed to create 'INSERT' statement\n.");
    }
    else if (result >= sizeof(str))
    {
        fprintf(stderr, "Failed to create 'INSERT' statement: truncated\n");
    }
    else
    {
        printf("[%s]\n", str);
    }
}

You declare this:

char in[50] = "INSERT INTO `Test` (`Col1`, `Col2`) VALUES ('1', '";

but

sizeof "INSERT INTO `Test` (`Col1`, `Col2`) VALUES ('1', '"

is 51 characters.

Which means that there is not enough room for the null terminator in your original in array, so in is not a string so can you cannot concatenate anything to it and as hmdj wrote even if it was a string there would be no room left to concatenate anything as it is full.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM