【问题标题】:K+R 2.4: bus error when assigning (Mac OS) [duplicate]K+R 2.4:分配时出现总线错误(Mac OS)[重复]
【发布时间】:2018-06-03 05:24:20
【问题描述】:

我目前正在尝试解决 K+R 书中的练习 2.4,但遇到了一个我无法在其他地方真正重现的奇怪错误。我正在使用:

Apple LLVM version 8.0.0 (clang-800.0.42.1)
Target: x86_64-apple-darwin16.4.0
Thread model: posix
InstalledDir: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin

代码是:

#include <stdio.h>
#include <string.h>

/*
 * Write an alternate version of `squeeze(s1, s2)' that deletes each 
character
 * in s1 that matches any character in the string s2.
 */

void squeeze(char *s1, const char *s2);

int main(int argc, char **argv) {
  char *tests[] = {"hello", "world", "these", "are", "some", "tests"};
  for (unsigned int i = 0; i < sizeof(tests) / sizeof(tests[0]); i++) {
    printf("'%s' = ", tests[i]);
    squeeze(tests[i], "aeiou");
    printf("'%s'\n", tests[i]);
  }
  return 0;
}

void squeeze(char *s1, const char *s2) {
  const size_t s2len = strlen(s2);
  s1[0] = s1[0];
  unsigned int j = 0;
  for (unsigned int i = 0; s1[i] != '\0'; i++) {
    unsigned int k;
    for (k = 0; k < s2len; k++)
      if (s1[i] == s2[k]) break;
    if (k == s2len)  // we checked every character once, didn't find a bad char
      s1[j++] = s1[i];
  }
  s1[j] = '\0';
}

GDB 说:

Thread 2 received signal SIGBUS, Bus error.
0x0000000100000e57 in squeeze (s1=0x100000f78 "hello", s2=0x100000fa1 
"aeiou")
at exercise2-4.c:23
23    s1[0] = s1[0];

错误最初发生在s1[j++] = s1[i],但我插入s1[0] = s1[0] 以独立于变量对其进行测试,并且它也在那里发生。显然,我在这里遗漏了一些东西。

如果有任何相关性,我正在使用clang -O0 -g -Weverything exercise2-4.c -o exercise2-4 进行编译。

非常感谢您抽出宝贵的时间,如果这个问题之前已经回答过,我很抱歉,我没有发现任何问题发生在如此奇怪的地方。

【问题讨论】:

  • 如果你想写K&R风格C,我觉得你需要clang -std=c89
  • 你说得对,谢谢@MarkSetchell

标签: c string string-literals sigbus


【解决方案1】:

您不能更改字符串文字。任何更改字符串文字的尝试都会导致未定义的行为。

来自 C 标准(6.4.5 字符串文字)

7 不确定这些数组是否不同,前提是它们的 元素具有适当的值。 如果程序试图 修改这样的数组,行为未定义。

而不是指向字符串字面量的指针数组

char *tests[] = {"hello", "world", "these", "are", "some", "tests"};

你应该声明一个二维字符数组。例如

char tests[][6] = {"hello", "world", "these", "are", "some", "tests"};

如果要向数组中添加新字符,还必须为数组的每个元素保留足够的空间。

【讨论】:

  • 天啊,当然!谢谢。
猜你喜欢
  • 2011-09-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-04-25
  • 1970-01-01
  • 1970-01-01
  • 2011-10-02
  • 2012-09-21
相关资源
最近更新 更多