【问题标题】:strncat off by one error - K&R C exercise 5-5strncat off by one error - K&R C 练习 5-5
【发布时间】:2014-09-13 17:16:32
【问题描述】:

我的 strncat 版本将一个太多字符复制到目标中,我不知道为什么。

#include <stdio.h>
#define MAX_CHARS 20

void nconcatenate(char *start, char *end, int n)
{
  if(sizeof start + n > MAX_CHARS)
    return;

  while(*start++);
  start--; /* now points to the final char of start, the \0 */
  int i;
  for(i = 0; (*start++ = *end++) && i < n; i++);
  *start = '\0';
}

int main()
{
  char start[MAX_CHARS] = "str";
  char *end = "ingy!";
  nconcatenate(start, end, 3);
  printf("start = %s\n", start);
  return 0;
}

使用 3 作为“n”个输出

stringy

这是一个太多的字符。

【问题讨论】:

  • 你在调试器中单步调试过代码吗?
  • sizeof start 将始终返回 sizeof(char*) 顺便说一句。
  • @OldProgrammer 我已经尝试过使用 gdb,尽管我仍然是使用它的初学者
  • @EdS。啊,当然,谢谢
  • @EdS。如果我不能以我使用的方式使用 sizeof,我将如何检查 start + n 的大小是否小于 MAX_CHARS?我只能考虑向函数传递另一个参数,但我宁愿不这样做。

标签: c string char off-by-one


【解决方案1】:

可能是因为条件

(*start++ = *end++) && i < n

首先检查 (*start++ = *end++),然后检查 i

我没有测试过,但检查一下看看。

【讨论】:

  • 太棒了,已经修复了它,我永远不会发现它。谢谢
猜你喜欢
  • 2020-06-25
  • 2012-11-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-21
  • 1970-01-01
  • 1970-01-01
  • 2016-04-12
相关资源
最近更新 更多