【问题标题】:Why does replacing char[] with char* produce bus error?为什么用 char* 替换 char[] 会产生总线错误?
【发布时间】:2021-04-03 07:41:02
【问题描述】:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int comp(const void *a, const void *b) {
   const char *ia = (const char*)a;
   const char *ib = (const char*)b;
   return (*ia - *ib);
}



int main(int argc, char *argv[]){
   char *temp1 = "hello";
   char temp[] = "hello";

   qsort(temp, strlen(temp), sizeof(char), comp);
   printf ("%s\n", temp);

/*
   qsort(temp1, strlen(temp1), sizeof(char), comp);
   printf ("%s\n", temp1); 
*/
}

在对字符串进行排序的 qsort 调用中,此处显示的代码如图所示工作(我的意思是它对字符串“hello”进行排序)。但是,当我取消注释掉最后两行的注释时(从而对 temp1 进行排序),它在 mac pro 上因总线错误而崩溃。 cc上的版本信息显示:

Apple LLVM 版本 10.0.0 (clang-1000.10.44.4) 目标:x86_64-apple-darwin17.7.0 线程模型:posix

我想知道为什么它会产生总线错误。

【问题讨论】:

  • 也许问题是在方法 qsort() 中的第一个参数是 char 或字符串数​​组,但您传递的是一个引用。尝试传递 *temp1,即再次使用星号,这再次将引用更改为对象
  • Initializing a char pointer in C. Why considered dangerous?。您的问题的防御/安全编程答案是,您应该明确声明 temp1 为指向 const 的指针,即 const char *temp1 = "hello";,这将导致在编译时捕获 const 违规。

标签: arrays c pointers constants


【解决方案1】:
char *temp1 = "hello"; // pointer to a const string

temp1 指向一个字符串文字。你不能修改它。 qsort() 函数试图修改它。这就是出错的原因。

char temp[] = "hello"; //const pointer to a string

这里可以修改数组内容。这就是它起作用的原因。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-11
    • 2011-02-23
    • 1970-01-01
    • 2018-03-15
    • 2021-05-07
    • 1970-01-01
    相关资源
    最近更新 更多