C - reading a file and segmentation fault [closed]

2019-09-08 04:32发布

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...

3条回答
混吃等死
2楼-- · 2019-09-08 05:04
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.

查看更多
Juvenile、少年°
3楼-- · 2019-09-08 05:08

change

char* buff[67108864]

to

char buff[67108864]

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

查看更多
forever°为你锁心
4楼-- · 2019-09-08 05:14

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

查看更多
登录 后发表回答