当大小足够大时,为什么此数组分配失败?

时间:2018-10-03 17:30:55

标签: c arrays malloc

当我遇到以下问题时,我正在尝试测试一种进行置换的替代方法。

当变量大小等于26(字母的大小)时,代码运行良好,但是如果变量足够大,则代码失败,但是如果我按代码中的定义进行操作并删除两个 for 跟随的循环没有问题。所以分配不是问题,循环似乎是问题,但是只有当 size 足够大时,这没关系,因为现在的代码是正确的,我只处理第一个26个元素,怎么回事?

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

static const char alphabet[] = "abcdefghijklmnopqrstuvwxyz";
static const int alphabetSize = sizeof(alphabet) - 1;

int main(void)
{
    long size = 8353082582; // 26^6 + 25^5 + 26^4 ...
    char* words[size];

    for (int i=0; i < strlen(alphabet); ++i)
    {
        words[i] = malloc(sizeof(char));
        if (words[i] == NULL) {
            printf("Memory allocation failed\n");
        }
        strncpy(words[i], &alphabet[i], sizeof(char));
    }

    for (int i=0; i < strlen(alphabet); ++i)
        printf("%s\n",words[i]);

    return 0;
}

返回

Segmentation fault: 11

0 个答案:

没有答案
相关问题