请问Mac端 bus error 怎么解决?

作者站长头像
站长
· 阅读数 30

写了一段代码,感觉没有问题,mac上运行就是报错 bus error,去 win 上测试了一下完全没问题,烦死了,也不知道怎么改。

#include<stdio.h>
#include<stdlib.h>
typedef struct Complex_Node {
    float real;
    float imaginary;
    struct Complex_Node *next;  
}Node;

void Init(Node* address){
    address = (Node*)malloc(sizeof(Node));
    if(address == NULL){
        printf("ERROR");
        return;
    }
    (*address).next = NULL;
    return;
}
void Add(Node* address,float real_part,float image_part){
// 这边没有加判断条件,就是做个测试,而且初始化后是空的,就直接加到头节点后面了
    Node* p;

    (*p).real = real_part;
    (*p).imaginary = image_part;
    (*p).next = NULL;
    (*address).next = p; // 经过测试,不访问 p 地址就不报错,但不知道怎么改


    return;
}
// void get(Node* address){
//     Node * p = address;
//     while (p!=NULL)
//     {
//         printf("%f",(*p).real);
//         printf("%f",(*p).imaginary);
//         p = (*p).next;
//     }
// }
int main(){
    Node* index;
    Init(index);
    Add(index,0.5,1.0);
}
回复
1个回答
avatar
test
2024-07-16
mac: bus error
linux: segment fault

两个系统上都是同样的错误:段错误,一般是访问了一段错误的内存。

在你这个例子中,index是一个uninitialized pointer,指向的位置是“随机”的。可能你想在Init里面初始化它,正如zxdposter所说,因为写法错误,实际上并没有初始化成功。

加两个printf很容易就能看出来:

// 修改1:
void Init(Node* address){
    address = (Node*)malloc(sizeof(Node));
    if(address == NULL){
        printf("ERROR");
        return;
    }
    (*address).next = NULL;
    printf("address = %p\n", address);
    return;
}

// 修改2:
int main(){
    Node* index;
    printf("1 index = %p\n", index);
    Init(index);
    printf("2 index = %p\n", index);
    Add(index,0.5,1.0);
}

在 mac 上

% ./a.out
1 index = 0x10e1cc025
address = 0x7f81b54057f0
2 index = 0x10e1cc025
bus error  ./a.out

在linux下:

$ ./a.out 
1 index = (nil)
address = 0x1c92010
2 index = (nil)
Segmentation fault

可见,mac和linux下index都没有被正确设置。

至于windows下为什么可以运行,纯属巧合。我没有这个环境,无法做更多验证。

回复
likes
适合作为回答的
  • 经过验证的有效解决办法
  • 自己的经验指引,对解决问题有帮助
  • 遵循 Markdown 语法排版,代码语义正确
不该作为回答的
  • 询问内容细节或回复楼层
  • 与题目无关的内容
  • “赞”“顶”“同问”“看手册”“解决了没”等毫无意义的内容