You need to enable JavaScript to run this app. C++项目运行Xcode报Thread 1: EXC_BAD_ACCESS(code=1)错误如何解决
优惠活动
大模型
产品
解决方案
定价
更多

C++项目运行Xcode报Thread 1: EXC_BAD_ACCESS(code=1)错误如何解决

问题诊断与修复方案

核心错误原因

  • 数组索引越界:内层循环变量j按像素字节遍历,步长为3,取值范围为0 ~ width*3,但array_bmp第二维长度仅为width,合法下标范围是0 ~ width-1,直接用j作为下标会严重超出数组边界,访问非法内存触发EXC_BAD_ACCESS错误。正确的像素列索引应为j/3,对应每3个字节表示1个像素的规则。
  • 可变长度数组栈溢出:int array_bmp[height][width]属于C语言的可变长度数组特性,并不被C标准支持,Xcode的Clang编译器虽然做了扩展兼容,但会将这类数组分配在栈空间。栈空间通常仅为几MB,若BMP分辨率稍高(如1920*1080)会直接栈溢出,触发内存访问错误。建议改用C标准容器std::vector实现动态数组,分配在堆空间避免栈溢出。
  • 缺少错误校验:未判断fopen返回值,若文件路径错误、文件不存在,f会返回NULL,后续fread操作访问空指针也会触发崩溃。请确认代码中/…/second.bmp为实际存在的有效绝对路径,可直接将BMP文件拖入Xcode终端获取正确路径。

修复后代码

#include <iostream>
#include <vector>
using namespace std;

int main()
{
    const char* filename = "/替换为实际的BMP文件路径/second.bmp";      
    FILE* f = fopen(filename, "rb");
    // 新增文件打开失败校验
    if (f == NULL) {
        cout << "文件打开失败,请检查路径是否正确" << endl;
        return 1;
    }
    char info[54];
    fread(info, sizeof(char), 54, f);
    int width = *(int*)&info[18];
    int height = *(int*)&info[22];

    cout << "  Name: " << filename << endl;
    cout << " Width: " << width << endl;
    cout << "Height: " << height << endl;
    cout << endl;

    int row_padded = (width * 3 + 3) & (~3);
    unsigned char* data = new unsigned char[row_padded];
    // 替换可变长度数组为vector,分配堆空间
    vector<vector<int>> array_bmp(height, vector<int>(width));

    for(int i = 0; i < height; i++)
    {
        fread(data, sizeof(char), row_padded, f);
        for(int j = 0; j < width*3; j += 3)
        {      
            // 像素亮度计算公式 Y = 0.3 * R + 0.59 * G + 0.11 * B
            // 修正索引为j/3
            array_bmp[i][j/3] = 0.3 * (int)data[j+2] + 0.59 * (int)data[j+1] + 0.11 *  (int)data[j];
        }
    }
    delete[] data;
    fclose(f);

    // 后续可正常使用array_bmp数组处理
    return 0;
}

内容的提问来源于stack exchange,提问作者Aver666

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.19 11:36:03