【问题标题】:Program received signal: “EXC_BAD_ACCESS”?程序接收信号:“EXC_BAD_ACCESS”?
【发布时间】:2012-06-27 09:34:07
【问题描述】:

我正在制作这个只读取文件内容的小程序,但是当我运行它时,我得到了这个错误:程序收到信号:“EXC_BAD_ACCESS”。

在我的代码 (main.c) 的第 10 行,我还收到了来自 Xcode 的警告:“Assignment make pointer from integer without a cast”:

#include <stdio.h>
#include <stdlib.h>

#define FILE_LOCATION "../../Data"

int main (int argc, const char * argv[]) {
    FILE *dataFile;
    char c;

    if ( dataFile = fopen(FILE_LOCATION, "r") == NULL ) {
        printf("FAILURE!");
        exit(1);
    }

    while ( (c = fgetc(dataFile)) != EOF ) {
        printf("%c", c);
    }

    fclose(dataFile);

    return 0;
}

这是调试器输出:

[Session started at 2012-06-27 10:28:13 +0200.]
GNU gdb 6.3.50-20050815 (Apple version gdb-1515) (Sat Jan 15 08:33:48 UTC 2011)
Copyright 2004 Free Software Foundation, Inc.
GDB is free software, covered by the GNU General Public License, and you are
welcome to change it and/or distribute copies of it under certain conditions.
Type "show copying" to see the conditions.
There is absolutely no warranty for GDB.  Type "show warranty" for details.
This GDB was configured as "x86_64-apple-darwin".tty /dev/ttys000
Loading program into debugger…
Program loaded.
run
[Switching to process 34331]
Running…
Program received signal:  “EXC_BAD_ACCESS”.
sharedlibrary apply-load-rules all
(gdb)

是不是指针有问题,功能不对?我发现了一个用来跟踪内存问题的东西,叫做 NSZombie,那是什么,我可以使用它吗?

【问题讨论】:

  • if ( (dataFile = fopen(FILE_LOCATION, "r")) == NULL ) {
  • @wildplasser:这应该是一个答案而不是评论。
  • 为您服务。 (但我认为这对于 Q/A 来说太微不足道了)
  • 既然你提到了 NSZombie:NSZombie 是一个 Objective-C 类,用于跟踪 Objective-C 对象的内存/生命周期管理中的错误。在 C 代码中不相关。

标签: c xcode string pointers fgets


【解决方案1】:
if ( (dataFile = fopen(FILE_LOCATION, "r")) == NULL ) {

【讨论】:

  • +1。如果您可以添加这是关于运算符优先级的,那就太好了。即=== 绑定更紧密。
  • 奇怪的是他并没有在 fgetc() 行中犯同样的错误。 (他又犯了一个错误 ;-)
【解决方案2】:

这是另一个错误:

char c;

while ( (c = fgetc(dataFile)) != EOF ) {

在使用fgetc() 等重要功能之前,您应该认真研究documentation

具体来说,fgetc() 返回int,这是匹配EOF 值所必需的。如果它返回char,则必须有一个字符的数值与EOF 冲突,因此不能出现在二进制文件中。那会很糟糕,所以这不是它的工作方式。 :)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-09
    • 2012-10-05
    • 1970-01-01
    • 2011-03-06
    • 1970-01-01
    相关资源
    最近更新 更多