c++ - Xcode 错误 : “EXC_BAD_ACCESS”

标签 c++ c xcode macos file

我正在尝试在 Xcode 中编译和运行测试 C 程序。该程序从文本文件中读取 5 个符号并将其关闭。程序构建成功,但当我尝试运行程序时出现错误:GDB:程序收到信号:fclose(in) 附近的“EXC_BAD_ACCESS”。

#include <iostream>
#include <unistd.h>

int main (int argc, const char * argv[])
{
    bool b;
    char inpath[PATH_MAX];
    printf("Enter input file path :\r\n");
    std::cin >> inpath;
    FILE *in = fopen(inpath, "r+w");
    char buf[5];
    fread(&buf,sizeof(buf),5,in);
    printf(buf);
    fclose(in);
    return 0;
}

这可能是什么原因造成的?

最佳答案

啊! sizeof(buf) 将返回 5,因此您在 5 字节缓冲区中请求 25 字节。这会覆盖自动存储并破坏 in

当然,请注意 fprint(buf) 将尝试打印一个没有终止 null 的缓冲区,因此它会打印超出读取内容末尾的垃圾。

关于c++ - Xcode 错误 : “EXC_BAD_ACCESS” ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9134446/

相关文章:

C 如何计算文本文件中唯一城市的数量

ios - 无法插入新 socket ?

c++ - 如何使用openssl获取AES-CCM解密的Tag信息

c++ - 空间有限的优先级队列 : looking for a good algorithm

c - linux c中的串行通信

c - C 中的链表;分段故障

c++ - 什么是复制省略和返回值优化?

c++ - 如何防止过度打字

xcode - NSBundle pathForResource 返回带有子目录的 nil

ios - 对于在 cellForItemAt 中将 isSelected 设置为 true 的单元格,为什么 UICollectionView 未将 isSelected 设置为 false?