Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 490
alexparkjw Avatar asked Feb 11 '26 16:02

alexparkjw


2 Answers

fscanf is trying to write data into *arr[i] which you haven't allocated. You only allocated arr[i] (which you didn't initialize either).

like image 199
emlai Avatar answered Feb 15 '26 08:02

emlai


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

like image 40
BlackMamba Avatar answered Feb 15 '26 07:02

BlackMamba



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!