简体   繁体   中英

Segmentation Fault while assigning int to array

I am try to read a line from a file, separate the chars, and then read them to a malloc'ed int array. I seem to be getting a segmentation fault when I use atoi to cast the char to an int, and thus I am unable to assign the int to the array. Any help would be appreciated.

int main(int argc, char * argv[]){

    FILE *in;
    in = fopen(argv[1], "r");
    FILE *out;
    out = fopen(argv[2], "w");

    int numDays;
    char ignore[256];
    fscanf(in, "%d", &numDays);
    fgets(ignore, sizeof(ignore), in);

    int *timeArray = (int *) malloc(numDays * sizeof(int)); ;

    char buffer[256];
    fgets(buffer, 256, in);

    const char delimiter[2] = " ";
    char *token;
    token = strtok(buffer, delimiter);
    int index = 0;
    while( token != NULL ) {
        printf( "%s\n", token);
        token = strtok(NULL, delimiter);
        int val = atoi(token);
        timeArray[index] = val;
        index++;
    }
    return(0);
}

When no tokens are left, strtok() returns NULL . But you call atoi(token) on it immediately, which will crash if it is NULL . The loop condition while (token != NULL) doesn't help because it isn't checked until the end of the loop body.

You need to restructure the loop so that the test is done before you try to use the result.

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