我对C编程相当陌生,并试图正确理解C中内存管理的细节.

我做了一个简单的程序,它可以编译,没有任何问题,但在调试过程中,在第printf("The next line gives a segmentation error");行之后出现分段错误

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>      // Here you have the isdigit macro

int main()
{
    FILE *filePtr; 
    char fileStr[150];      // Buffer for reading file.

    filePtr = fopen("ManyRandomNumbersLog.txt", "r");
    
    printf("\n\nNow reading the file:\n");

    while (!feof(filePtr))
    {
        printf("The next line is a segmentation fault!\n");
        // WHYYYY?!?!?!?
        fgets(fileStr, 150, filePtr);
        printf("%s\n", fileStr);
    }

    return 0;
}

fgets函数调用似乎给出了这个错误,因为指针有以下"Error?"在它里面:

file pointer error

你知道问题是什么吗?知道如何预防吗?

我试着调试它,但找不出为什么指针无法访问该内存.

推荐答案

始终判断文件是否已成功打开.Also feof does not work the way you think.

int main()
{
    FILE* filePtr; 
    char fileStr[150];      // Buffer for reading file.

    filePtr = fopen("ManyRandomNumbersLog.txt","r");
    
    if(filePtr)
    {
        printf("\n\nNow reading the file:\n");
        while(fgets(fileStr, 150, filePtr))
        {
            printf("%s\n",fileStr);  
            //filestr will also contain '\n' at the end if it was present in the file.
        }
        fclose(filePtr);
    }

    return 0;
}

PS不要查看文件 struct ,因为它不会给您任何有价值的信息.

C++相关问答推荐

与unions 的未定义行为

通过MQTT/蚊子发送大文件—限制在4MB

如何创建由符号组成的垂直结果图形?

为什么我一直收到分段错误?

Rust FFI--如何用给出返回引用的迭代器包装C风格的迭代器?

在 struct 中强制转换空指针

为什么memcpy进入缓冲区和指向缓冲区的指针工作相同?

理解bzip2的BZ2_解压缩函数中的状态重新分配

有没有一种方法可以用C创建保留限定符的函数?

为什么Linux无法映射这个PT_LOAD ELF段?

宏观;S C调深度

向左移位3如何得到以字节为单位的位数?

Linux Posix消息队列

C: NULL>;NULL总是false?

在分配内存后使用指针是未定义的行为吗?

无法理解 fgets 输出

System V 消息队列由于某种原因定期重置

多行表达式:C 编译器如何处理换行符?

C23 中的 [[reproducible]] 和 [[unsequenced]] 属性是什么?什么时候应该使用它们?

无法在 C 中打开文本文件,我想从中读取文本作为数据并将其写入数组