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

时间:2017-10-06 06:01:14

标签: c

这是一个用.txt文件中的单词填充char指针数组的程序。为什么以下代码返回分段错误?任何帮助表示赞赏

#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;
}

错误 -

Segmentation Fault (core dumped)

1 个答案:

答案 0 :(得分:3)

NumberOfElements = sizeof(username)/sizeof(username[0]);

将始终返回100,如果输入少于80个字,则用户名中的其余元素将不会被分配内存,因此当您打印未分配的指针时,将导致未定义的行为

打印num_words时应该循环到username[p],而不是循环到NumberOfElements

相关问题