C - reading a file and segmentation fault [closed]

假装没事ソ 提交于 2019-12-12 00:53:42

问题


Im writing a program in C (eclipse in linux) so I need to open a big text file and read it (and than try with diffrent size of buffer each time)

Anyways, this is the code and I don't understand why Im getting segmentation fault from the open function

int main(void)
{
    int fd;
    char* buff[67108864];
    FILE *testfile;
    double dif;
    fd = open("testfile.txt", O_RDONLY);
    if (fd>=0) {
        read(fd,buff,67108864);
        close(fd);      }

    return 0;
}

I have edited my question but now if I change my buffer to the biggest size I need (67108864 bytes) im still getting segmentation fault...


回答1:


well if you want to allocate memory into buff, you need to make it a pointer..

char* buff;

also notice you only allocate one char.. you should consider that, I think you want to use more memory..

another common thing is not using dynamic memory for file reading..

try:

char buff[100]; 

and then just the same code...

read(fd,buff,100));

and then just keep reading until the find is complete, read returns the amount of bytes actually read.

Also like commented above, you are using testfile before initializing it.. that is also an access violation




回答2:


char buff;

should be a pointer

char *buff;

Also after reading read(fd,buff,(sizeof(char))); you should allocate more memory to buff with realloc.




回答3:


change

char* buff[67108864]

to

char buff[67108864]

what you need is a char array, not a char point array.



来源:https://stackoverflow.com/questions/15617949/c-reading-a-file-and-segmentation-fault

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