简体   繁体   English

fscanf导致段错误

[英]fscanf resulting in segfault

I'm trying to read a bunch of int s from a .txt file and store them in memory. 我正在尝试从.txt文件中读取一堆int并将其存储在内存中。 The fscanf() line in the below code is causing a segmentation fault whenever I try to run it, though. 每当我尝试运行它时,以下代码中的fscanf()行都会导致分段错误。 I've confirmed that `fopen() is working properly. 我已经确认`fopen()工作正常。 Any idea what I should do? 知道我该怎么办吗? Thanks for your help. 谢谢你的帮助。

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




void load_file(FILE* file, int** p);

int main()
{

    FILE* f1;
    f1 = fopen("twenty-five-ints.txt", "r");
    int p=0;
    int* k = &p;
    load_file(f1, &k);
    return 0;
}

void load_file(FILE* file, int** p) {

    int number = 0;
    int i = 0;
    while (fscanf(file, "%d", &number) != EOF) {
        *(*p + i) = (int) fscanf(file, "%d", &number);
        i++;
    }

}

In your code, p points to a pointer which points to a single integer. 在您的代码中, p指向一个指向单个整数的指针。 You only have enough space to store a single integer, attempting to store a second or third integer likely causes the crash you observe. 您只有足够的空间来存储单个整数,尝试存储第二个或第三个整数可能会导致崩溃。

The problem is in 问题出在

*(*p + i) = (int) fscanf(file, "%d", &number);

you have passed the address of a single int , and you're prerforming arithmatic opeation on the pointer to take it beyond the accessible memory. 您已经传递了一个int的地址,并且正在对指针进行算术运算,以使其超出可访问的内存范围。 Accessing that memory invokes undefined behavior . 访问该内存会调用未定义的行为

A segmentation fault is one of the side effects of UB. 分段错误是UB的副作用之一。

That said, FWIW, there is no reason to cast the return value of fsacnf() to int . 就是说,FWIW,没有理由将fsacnf()的返回值fsacnf()int

Allocate p as an array of size 25 and initialize each element to zero. 将p分配为大小为25的数组,并将每个元素初始化为零。

That should solve the problem 那应该解决问题

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

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