0

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

我还收到了来自 Xcode 的警告:在我的代码 (main.c) 的第 10 行“赋值从整数中生成指针而不进行强制转换”:

#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,那是什么,我可以使用它吗?

4

2 回答 2

2
if ( (dataFile = fopen(FILE_LOCATION, "r")) == NULL ) {
于 2012-06-27T09:39:44.357 回答
1

这是另一个错误:

char c;

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

您应该在使用它们之前真正研究重要功能的文档。fgetc()

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

于 2012-06-27T09:45:07.007 回答