Segmentation fault (core dumped) when using fscanf to read into a pointer

霸气de小男生 提交于 2019-12-09 04:02:17

问题


I'm trying to use fscanf to read and print every character on the screen, but I'm getting a segmentation fault (core dumped) when I run the program. Here's my code:

#include <stdio.h>

main(int argc, char * argv[]) {
    int *a ;
    FILE *input;

    if (argc>=2) {
        input= fopen(argv[1],"r");

        if (input!=NULL) {
            while (feof(input)==0) {
                fscanf(input,"%d\n",a);
                printf("%d\n",*a);
            }
            fclose(input);
        } else {
            printf("Error!\n");
        }
    }
}

I provide the file as an argument, like this:

./myprog input.txt

The file input.txt contains this:

23
47
55
70

回答1:


Variable a is not initialized to point to a valid memory address.

Therefore, it is most likely pointing to an invalid memory address.

Here is one way to fix it:

int *a = malloc(sizeof(int));
...
free(a); // when done using it

Here is another way to fix it:

int b;
int *a = &b;

But I suggest that you follow the steps below in order to make it simpler and cleaner...


Change this:

int *a;

To this:

int a;

And this:

fscanf(input,"%d\n",a);

To this:

fscanf(input,"%d\n",&a);



回答2:


When you write:

int *a;

then a is a pointer, but currently it does not point anywhere.

You have to make it point to valid storage for an int, before you supply it to fscanf.

For example, inside main():

int b;
a = &b;
fscanf(input,"%d\n",a);

Also, your loop is wrong. It is almost always an error to use feof (let alone, as a loop condition). Instead, you should test the actual read operation. In your case:

while ( 1 == fscanf(input,"%d\n",a) )
{
     printf("%d\n", a);
}


来源:https://stackoverflow.com/questions/23709822/segmentation-fault-core-dumped-when-using-fscanf-to-read-into-a-pointer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!