Get a segment fault while reading a file

末鹿安然 提交于 2019-12-10 10:46:51

问题


I want to read the whole file content and print it out , but I get a segment fault , I can't find what's wrong with the code ...

#include <stdio.h>
#include <stdlib.h>
int main()
{
    FILE * file;
    long fsize;
    file = fopen("./input.txt","r");
    if(file != NULL){

        //get file size
        fseek(file,0,SEEK_END);
        fsize = ftell(file);
        rewind(file);

        // print
        char * file_content;
        fgets(file_content,fsize,file);
        puts(file_content);
    }
    else{
        printf("open failure\n");
    }
    fclose(file);

    return 0;
}

回答1:


The pointer you pass to fgets (file_content) is uninitialized. It should be pointing to a block of memory large enough to contain the specified number (fsize) of bytes. You can use malloc to allocate the memory.

char* file_content = (char*)malloc(fsize);



回答2:


char * file_content is just a pointer, you need to allocate memory to store the string.

char * file_content;
file_content = malloc(fsize);



回答3:


"..but I get a segment fault"

Obviously because you're attempting to write to an uninitialized file_content

Allocated memory for file_content before use

char * file_content =malloc(fsize);


来源:https://stackoverflow.com/questions/18701924/get-a-segment-fault-while-reading-a-file

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