【发布时间】: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