【问题标题】:C, Malformed int to char[] after strcatC,在 strcat 之后将格式错误的 int 转换为 char[]
【发布时间】:2015-01-27 20:18:38
【问题描述】:

当打印一个带有 int 值的 char[] 时,int 不正确。但是sprintf之后的str的printf输出正确的值。

我正在使用此代码:

  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);
   }

输出:INSERT INTO Test (Col1, Col2) VALUES ('1', 'A&amp;?0')

【问题讨论】:

  • p.s 如果有人可以提出一种更清洁或更有效的构建字符串的方法,请说:)
  • int size = snprintf(NULL, "INSERT INTO 'Test' ('Col1', 'Col2') VALUES ('1', '%d')", i); 将为您提供数组的最小大小。
  • 顺便说一句,如果只是在最后打印f,就像在您的代码提取中一样,只需忘记str,in和2 strcat,只需在一行代码中使用printf

标签: c


【解决方案1】:

in 太小,因为字符串文字是 50 字符,这意味着之后的 strcat() 写入超出缓冲区的末尾导致未定义的行为,在这种情况下会导致损坏(实际上字符串文字是 @ 987654325@ 由于附加到字符串文字的隐式空终止符)。纠正增加缓冲区的大小并使用snprintf() 来防止缓冲区溢出并在单个操作中执行字符串构造。例如:

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);
    }
}

【讨论】:

  • 好点 :) 当我使用 snprintf 时出现分段错误,但使用 sprintf 可以正确执行。
【解决方案2】:

你声明:

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

但是

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

是 51 个字符。

这意味着在您的原始in 数组中没有足够的空间用于空终止符,因此in 不是字符串,因此您不能将任何内容连接到它,正如hmdj 所写,即使它是字符串已满,将没有空间连接任何内容。

【讨论】:

    猜你喜欢
    • 2015-01-20
    • 1970-01-01
    • 1970-01-01
    • 2015-12-18
    • 2015-01-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多