c - K+R 2.4 : bus error when assigning (Mac OS)

标签 c string string-literals sigbus

我目前正在尝试解决 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 进行编译如果这有任何相关性的话。

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

最佳答案

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

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

7 It is unspecified whether these arrays are distinct provided their elements have the appropriate values. If the program attempts to modify such an array, the behavior is undefined.

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

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

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

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

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

关于c - K+R 2.4 : bus error when assigning (Mac OS),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47909618/

相关文章:

php - 字符串分配中的累积内存使用 : $a = $a . $b vs $a .= $b

c++ - 有没有办法从非 C/C++ 文件中读取 C++ 原始字符串文字的内容?

c - 错误: Expected Expression '/' before token

c - volatile integer 如何解决这个线程同步问题?

c - 同时使用代码页 437 和 setlocale

c - 在 C 中,指针值更改后内存值会发生什么情况?

c - 在两个字符串文字之间放置定义宏

c - 提交解决方案后Codechef网站中出现段错误

Swift rangeOfString 索引 0 或 1

c++ - 如何在不删除的情况下将\x1\x2\x3 ...字符转换为普通字符?