Search code examples
cpointersmallocscanfcoredump

fscanf() code does not always crash memory, but sometimes


=========================

code (file name is test.c)

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main(int argc, char * argv[] ) {
    int i=0, num=atoi(argv[1]);
    char **arr=(char**)malloc(num*sizeof(char*));
    FILE  *fp = fopen("test.txt","r");
    if( arr == NULL) { printf("out of memory\n"); exit(1); }
    if( fp == NULL) { printf("cannot open the file \n"); exit(1); }

    for(i=0; i< num; i++) fscanf(fp,"%s", arr+i ); // HERE
    printf("%s\n", arr+num-1 );

    fclose(fp);
    free(arr);
    return 0;
}

========

test.txt

watermelon
grape
strawberries
orange
peach
banana
mango
cherry
pineapple
apple
blueberry
raspberry
pear
melon
greengrapes
tangerine
kiwifruit
pomegranate
plum
nectarine

========

Question

when i excuted below several times

test 1
test 2
...
...
test 7
test 8

it crushes often something like "core dump" but working as i expected.

however, when i type higher than 9, it never crush...

test 9
test 10
...

enter image description here

what makes this code crash?


Solution

  • #include<stdio.h>
    #include<stdlib.h>
    #include<string.h>
    
    int main(int argc, const char * argv[])
    {
        int i = 0, num = atoi(argv[1]);
        char** arr = (char**)malloc(num * sizeof(char*));
        for (int j = 0; j < num; j++) {
            arr[j] = (char*)malloc(100 * sizeof(char));
        }
        FILE* fp = fopen("test.txt", "r");
        if (arr == NULL) {
            printf("out of memory\n");
            exit(1);
        }
        if (fp == NULL) {
            printf("cannot open the file\n");
            exit(1);
        }
    
        for (; i < num; i++) {
            fscanf(fp, "%s", arr[i]);
            printf("%s\n", arr[i]);
        }
        for (int k = 0; k < num; k++) {
            free(arr[i]);
        }
        free(arr);
        return 0;
    }
    

    for fscanf(fp, "%s", arr[i]);, you need alloc memory for each arr[i].