user3283146 user3283146 - 1 month ago 8
C Question

Why am I getting a segmentation fault from scanf loop?

The segmentation fault error disappears after commenting out the scanf loop. Why is that loop giving me a segmentation fault?

char** nameArray = malloc(numNames * sizeof(char *));

for(i =0; i< 10; i++) {
nameArray[i] = malloc(25 * sizeof(char));
}

for (i = 0; i< numNames; i++) {
scanf("%s", &nameArray[i]);
}

for (i =0; i<numNames; i++) {
free(nameArray[i]);
}

Answer

First you need to change

for(i =0; i< 10; i++) { 

to

for(i =0; i< numNames; i++) { 

as you need to create enough entries.

Also you need to change this line

scanf("%s", &nameArray[i]);

to

scanf("%s", nameArray[i]);

as nameArray[i] is a character pointer as required.

Also it would be better to use

scanf("%24s", nameArray[i]);

as this would prevent buffer overrun. Also it would be a good idea to check the return value of scant