strcat causing segmentation fault

ⅰ亾dé卋堺 提交于 2020-01-17 03:58:09

问题


This causes a segmentation fault:

char str1[60];
char**array;

array=malloc( str_nos * sizeof(char *) );
array[i]=malloc( str_len * sizeof(char *) );

strcat(array[i],str1);
strcat(array[i]," ");

str1 is taken from scanf and it's shorter than 60 characters. array[i] is from a dynamic array of strings.

Do you have any idea of what causes the problem? It happens only for a great amount of scanfs.


回答1:


At least two possibilities:

  • If the buffer pointed to by array[i] doesn't hold enough space, then you will overwrite the end of the buffer, which will often result in a seg-fault.

  • One of the strings isn't properly null-terminated, so strcat just starts walking through memory.




回答2:


Either array[i] is pointing to nowhere, or the length of the buffer pointed by array[i] is insufficient.

EDIT: According to the code you posted, the buffer pointed by array[i] initially contains uninitialized garbage. You can't apply strcat to a destination buffer that contains uninitialized garbage.

Either make your buffer to hold an empty string before trying to strcat anything to it

array[i][0] = '\0';
strcat(array[i],str1);
strcat(array[i]," ");

or, alternatively, start with strcpy and then do strcat

strcpy(array[i],str1);
strcat(array[i]," ");



回答3:


array[i]=malloc( str_len * sizeof(char *) );

What's i here? If i is not in the range [0,str_len), then you are accessing memory that you may not have permission to use...



来源:https://stackoverflow.com/questions/8249257/strcat-causing-segmentation-fault

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