简体   繁体   中英

Seg fault when using a variable to offset an array

I am trying to add one character at a time to a char array, called buffer. When I try to add a character to buffer[count], I get a segmentation fault. However if I try to add a character to buffer[0], buffer[1], or any other integer offset it runs fine. Here is my code:

#include <stdio.h>


int main(int argc, char *argv[]){
    FILE * fp;
    char buffer[100];

    fp = fopen(*(argv+1), "r");

    if(fp == NULL){
        printf("File \"%s\" not found!\n", *(argv+1));
        return 0;
    }

    int curr_char;
    unsigned int count = 0;
    unsigned int min_len;

    while(!feof(fp)){

        curr_char = fgetc(fp);

        if((curr_char >= 32) && (curr_char <= 126)){
            buffer[count] = curr_char;
            printf("%c", curr_char);
            count++;

            if(!((curr_char >= 32) && (curr_char <= 126))){
                break;
            }

        }
    }
}

Why is buffer[count] not allowed?

How can you access location 453 like this buffer[453] when your buffer is only of size 100? This is UB.

char buffer[100]; 

you only can access from buffer[0] to buffer[99] . In your code count maybe exceed 99 , so there might be a segment fault.

If your input file has more than 100 characters, your count will be greater than 100, and you will have a buffer overflow, that is undefined behavior, segmentation fault is one of the common possibilities.

Another common problem in your code is that you use feof() incorrectly, see “while( !feof( file ) )” is always wrong .

You can access memory only allocated to you when you say char buffer[100] it allocates 100 bytes in ram for you. say from the address 1001 to 1100. when you try to say buffer[453] it is internally converted to a statement like *(buffer + 453)

where buffer base address is 1001. and 453 is added to it then 1454th byte is tried to access which is not allowed as it may lead serious problems like (access data from other process and so on). so kernel halts user execution by sending a signal SIGSEGV

EDIT: as it count the file your reading from may have more than 100 bytes. which is again not in range of your process. try increases your buffer size say char buffer[1024]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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