程序收到信号:“EXC_BAD_ACCESS”?

时间:2012-06-27 09:34:07

标签: c xcode string pointers fgets

我正在创建这个只读取文件内容的小程序,但是当我运行它时出现此错误:程序收到信号:“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,那是什么,我可以使用吗?

2 个答案:

答案 0 :(得分:2)

if ( (dataFile = fopen(FILE_LOCATION, "r")) == NULL ) {

答案 1 :(得分:1)

这是另一个错误:

char c;

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

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

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