This question already has an answer here:
Why does char* cause undefined behaviour while char[] doesn't?
                                
                                    (1个答案)
                                
                        
                                2年前关闭。
            
                    
我目前正在尝试解决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不确定这些数组是否是唯一的,只要它们
  元素具有适当的值。如果程序尝试执行
  修改这样的数组,行为是不确定的。


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

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


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

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


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

关于c - K + R 2.4:分配时出现总线错误(Mac OS),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/47909618/

10-11 23:09
查看更多