Why am I getting a segmentation fault from scanf loop?

微笑、不失礼 提交于 2019-12-10 23:22:12

问题


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]);
}

回答1:


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




回答2:


It is because nameArray[i] is already a pointer, obtained from malloc, so you only need to pass that pointer to scanf, using

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

without the &.




回答3:


you have to take care of allocation ; in your case you allocate only 10 namearray elements

you have to make allocation for all variables you will scanf : change 10 with numNames

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

and the & sign is used with normale charls in pointer case don't use it ;

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


来源:https://stackoverflow.com/questions/40327254/why-am-i-getting-a-segmentation-fault-from-scanf-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!