简体   繁体   English

使用fscanf进行EXC_BAD_ACCESS

[英]EXC_BAD_ACCESS with fscanf

I have a file inp which looks like: 我有一个文件inp,看起来像:

123.456 one
111.111 two
222.222 three
444.444 four

I'm trying to read this file like: 我正在尝试读取此文件,如:

while(fscanf(inp, "%s %s", s1, s2) != EOF)

Where 123.456 stores in s1 (string) and "one" stores in s2 (string). 其中123.456存储在s1 (字符串)中,而"one"存储在s2 (字符串)中。

But I get this error: 但我得到这个错误:

Thread 1:EXC_BAD_ACCESS (code = 1, address = 0x48)

Any idea why or how to fix this error? 知道为什么或如何解决这个错误?

Here is my whole code: 这是我的整个代码:

int main(void)
{
FILE *inp;
char s1[15];
char s2[8];

inp = fopen("inputfile.txt", "r");

while(fscanf(inp, "%s %s", s1, s2) != EOF)
{
    printf("%s", s1);
}

return 0;
}

My debugging area shows that "123.456" is stored into s1 and "one" is stored into s2. 我的调试区域显示“123.456”存储在s1中,“1”存储在s2中。

There's nothing wrong with that code, other than the missing stdio.h include (a) . 除了缺少的stdio.h include (a)之外,该代码没有任何问题。 Therefore your problem either lies elsewhere (such as if you're compiling a different file) or your compiler is buggy (unlikely). 因此,您的问题要么在其他地方(例如,如果您正在编译不同的文件),要么您的编译器有问题(不太可能)。

You can find out if it's the first one by simply making a minor change: 你可以通过简单的改变来找出它是否是第一个:

#include <stdio.h>

int main (void) {
    FILE *inp;
    char s1[15];
    char s2[8];

    puts ("Hello from Pax");
    inp = fopen ("inputfile.txt", "r");
    if (inp == NULL) {
        puts ("Couldn't open input file");
    } else {
        while (fscanf (inp, "%s %s", s1, s2) != EOF) {
            printf ("[%s] [%s]\n", s1, s2);
        }
    }

    return 0;
}

and seeing if the new message comes out. 并查看新消息是否出来。 The change I'm suggesting for debugging is simply the Hello from Pax output but I've cleaned up the code a little more as well to catch some possible problems. 我建议调试的更改只是Hello from Pax输出的Hello from Pax但我已经清理了一些代码,以便捕获一些可能的问题。

On my system, that code outputs: 在我的系统上,该代码输出:

Hello from Pax
[123.456] [one]
[111.111] [two]
[222.222] [three]
[444.444] [four]

as expected. 正如所料。


(a) One possibility to watch out for is missing include files in systems where int and pointers are different widths. (a)需要注意的一种可能性是缺少包含int和指针宽度不同的系统中的文件。 If you have a compiler that assumes unprototyped functions accept int arguments, that may lead to parameters being extracted from the wrong place on the stack. 如果您的编译器假定非原型函数接受int参数,则可能导致从堆栈中的错误位置提取参数。

This answer shows this particular little foible in action for mismatched printf format specifiers and it's possible you may see the same behaviour from fscanf since it uses the same feature. 这个答案显示了针对不匹配的printf格式说明符的这个特殊的小问题,并且你可能会看到fscanf的相同行为,因为它使用相同的功能。

But that's just educated supposition on my part, it may not apply here. 但这只是我自己的教育假设,它可能不适用于此。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM