Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/61.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C 为什么会返回分段错误?_C - Fatal编程技术网

C 为什么会返回分段错误?

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

这是一个用.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 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]);