gpt4 book ai didi

c - 如何在 C 中为字符串数组分配内存 - malloc 错误

转载 作者:太空宇宙 更新时间:2023-11-04 05:47:43 25 4
gpt4 key购买 nike

问题: 我想为固定大小的字符串数组的元素分配内存,但是,我有 75% 的时间遇到​​崩溃。

那是我的程序运行完美的 25%,但错误是我以前没有遇到过的

#define PACKAGE_COUNT 60
#define MAX_COUNT 5

const char *colors[] = { "blue", "red", "yellow", "purple", "orange" };

char **generatePackage() {


char **generatedPackage = malloc(PACKAGE_COUNT);
int randomIndex = 0;

for (int i = 0; i <= PACKAGE_COUNT; ++i) {

randomIndex = rand() / (RAND_MAX / MAX_COUNT + 1);
generatedPackage[i] = malloc(sizeof(char) * sizeof(colors[randomIndex]));
// ERROR

strcpy((generatedPackage[i]), colors[randomIndex]);

// printf("generatePackage - %d: %s \n", i + 1, generatedPackage[i]);
}

return generatedPackage;
}

enter image description here enter image description here enter image description here

最佳答案

您没有考虑到指针的大小不是一个这一事实。因此,只分配了一小部分大小。因此,一些指针没有足够的内存分配,导致程序仅在访问其中一个时崩溃。

#define PACKAGE_COUNT 60
#define MAX_COUNT 5

const char *colors[] = { "blue", "red", "yellow", "purple", "orange" };

char **generatePackage() {
char **generatedPackage = malloc(PACKAGE_COUNT * sizeof(char*)); // The size of a pointer is not one, so this a multiplicative factor must be applied
int randomIndex = 0;

for (int i = 0; i < PACKAGE_COUNT; ++i) { // the upper bound is i < PACKAGE_COUNT, not i <= PACKAGE_COUNT

randomIndex = rand() / (RAND_MAX / MAX_COUNT + 1);
generatedPackage[i] = malloc(sizeof(char) * (strlen(colors[randomIndex]) + 1)); // You probably want to allocate enough space for the string, rather than enough space for the pointer, so you must use strlen

strcpy((generatedPackage[i]), colors[randomIndex]);

// printf("generatePackage - %d: %s \n", i + 1, generatedPackage[i]);
}

return generatedPackage;
}

关于c - 如何在 C 中为字符串数组分配内存 - malloc 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56102603/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com