gpt4 book ai didi

c - 重新分配返回 NULL

转载 作者:太空狗 更新时间:2023-10-29 15:05:22 27 4
gpt4 key购买 nike

int main() {
struct lottery *array;

array = (struct lottery *)malloc(3000 * sizeof(struct lottery));
int opt, counter;

menu1();
scanf("%d", &opt);
if (opt == 1)
Load(array, &counter);
else
exit("0");
menu2();
counter--;
scanf("%d", &opt);
while (opt != 7) {
switch (opt) {
case 1:
Save(array);
break;
case 2:
Enterd(array, &counter);
printf("%d\n", counter);
break;
}
menu2();
scanf("%d", &opt);
}
return 0;
}

void Enterd(struct lottery *a, int *count) {
struct lottery *b;
int x;

(*count)++;
x = *count;

printf("Your new data will have an ID of %d\n",x);
a[x].aa = x;

b = (struct lottery *)realloc(a, x * sizeof(struct lottery));
if (b == NULL) {
printf("Memory could not be allocated for your new input.Program will now exit...\n");
exit("0");
}

a = b;

printf("What is the date of your new draw?\n");
scanf("%d/%d/%d", &a[x].date1.day, &a[x].date1.month, &a[x].date1.year);
printf("Now please insert the 5 non-joker numbers\n");
scanf("%d%d%d%d%d", &a[x].n1, &a[x].n2, &a[x].n3, &a[x].n4, &a[x].n5);
printf("What is the 'Joker' number of this draw?\n");
scanf("%d", &a[x].joker);
printf("Your input is now complete.");
}

我正在写一个关于一些彩票文件的保护。我在向彩票数组添加更多数据的函数中遇到了这个问题。每当 x 包含 1989 时,我的 realloc 调用都会返回 NULL。我将 x 设置为 1985 并且 i 可以向数组添加 4 个输入,但是每当 x 为 1989 时,它仍然返回 。我的问题是:是代码有问题还是内存不足?

最佳答案

如果realloc 返回null,首先打印出你要求分配的内存量。如果它是一个负数或一个巨大的数额,那就有问题了。如果这是一个合理的数量,并且您的机器还算不错,那么您不太可能内存不足。所以 malloc() 系统一定以某种方式被破坏了。要么你传递了一个无效的指针,要么你已经写过了一个 block 的末尾,可能在程序的一个完全不相关的部分。

关于c - 重新分配返回 NULL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41765761/

27 4 0
文章推荐: c - C中的分而治之trominos算法
文章推荐: javascript - HTML5 文件系统 API
文章推荐: html - 使用 WebDriver 单击
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com