C 为什么会返回分段错误?
这是一个用.txt文件中的单词填充字符指针数组的程序。为什么下面的代码返回分段错误?谢谢你的帮助C 为什么会返回分段错误?,c,C,这是一个用.txt文件中的单词填充字符指针数组的程序。为什么下面的代码返回分段错误?谢谢你的帮助 #include <stdio.h> #include <stdlib.h> #include <string.h> void *emalloc(size_t s) { void *result = malloc(s); if (NULL == result) { fprintf(stderr, "Memory allocatio
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void *emalloc(size_t s) {
void *result = malloc(s);
if (NULL == result) {
fprintf(stderr, "Memory allocation failed!\n");
exit(EXIT_FAILURE);
}
return result;
}
int main()
{
#define SIZE 100
char *username[100];
char word[80];
int num_words = 0;
size_t p;
size_t NumberOfElements;
/* Read words into array */
while(1 == scanf("%s", word)) {
username[num_words] = emalloc((strlen(word) + 1) * sizeof(word[0]));
strcpy(username[num_words], word);
num_words++;
}
/* Print out array */
NumberOfElements = sizeof(username)/sizeof(username[0]);
printf("no. %lu\n", NumberOfElements);
for (p = 0; p < NumberOfElements; p++) {
printf("%s", username[p]);
}
return EXIT_SUCCESS;
}
将始终返回100,并且如果您输入的字数少于80个,则用户名中的其余元素将没有分配内存,因此当您打印未分配的指针时,将导致未定义的行为
打印
username[p]
时,应该循环到num\u words
,而不是循环到NumberOfElements
使用调试器并调试它?当使用调试器时,哪一行引发了错误?顺便问一下%lu
是大小的错误格式说明符,你应该使用%zu
,事实上它总是100
。谢谢你,不应该错过这个
Segmentation Fault (core dumped)
NumberOfElements = sizeof(username)/sizeof(username[0]);