gpt4 book ai didi

c - Realloc 最初有效,然后在多次重复后返回 null

转载 作者:太空宇宙 更新时间:2023-11-04 06:22:09 24 4
gpt4 key购买 nike

Realloc 最初适用于大小为 200 和 400 的数组,但随后由于我无法解析的原因意外返回大小为 800 的 null。

unsigned long ints 正在使用,因为 m 值很大,非常必要。可能吧。

我在 C 方面很糟糕。

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

/* Macros */
#define m 4294967161
#define a 2
#define r (m % a)
#define q (unsigned long) floor(m / a)

/* Method stubs */
[snip]

/* Initial array settings */
unsigned long elements = 0; // Number of elements in the array.
unsigned long size = 100; // Dynamically allocated size of the array.

/* Evaluates g(x) = ax mod m with no values > m - 1 */
unsigned long g(unsigned long x) {
[snip]
}

unsigned long compute() {
unsigned long i = 1;
unsigned long x = a;
unsigned long j = 0;
unsigned long *multipliers = 0;
initialize(&multipliers);

while (x != 1) {
if (((m % x) < (m / x)) && (gcd(i, m - 1) == 1)) {
add(x, multipliers);
j++;
}
i++;
x = g(x);
}
}

/* Initialize array. */
void initialize(unsigned long **multipliers) {
*multipliers = (unsigned long *)malloc(sizeof(unsigned long) * size);
}

/* Add element to an array. */
void add(unsigned long element, unsigned long *multipliers) {
if (elements >= size) {
printf("Inside elements >= size check.\n");
size = size * 2;
printf("Size is now %lu\n", size);
unsigned long *n_vector = NULL;
n_vector = (unsigned long *)realloc(multipliers, sizeof(unsigned long) * size);
printf("Reallocated.\n");

if (n_vector != NULL) {
printf("Copying n_vector to multipliers.\n");
multipliers = n_vector;
}
else
printf("n_vector is null.\n");
}
multipliers[elements++] = element;
return;
}

最佳答案

这是您的代码中有问题的部分:

void add(unsigned long element, unsigned long *multipliers) {
n_vector = realloc(multipliers, sizeof(unsigned long) * size);
multipliers = n_vector;
}

进入时,multipliers是指向由 malloc 分配的缓冲区的指针.你打电话realloc , 它返回缓冲区的新地址。新地址可能与旧地址相同,也可能不同。然后设置local 变量multipliers到新地址。但这是一个局部变量。当函数返回时,新地址不会存储在任何地方。此函数(compute 函数)的调用者仍在使用旧地址。

第一次调用 realloc 后更改地址,您最初可能不会注意到任何内容,因为旧地址仍然具有旧内容;但是当你写过旧的一端时,你可能会覆盖内存管理系统使用的数据结构。在您调用 realloc 的位置同样,您传递给它的参数是旧缓冲区的地址,此时,它不再指向 malloc 的缓冲区。/realloc正在管理。在这一点上,一切都乱套了。

解决方案:add需要将新地址返回给它的调用者。要么让它返回它(你可以,因为它目前什么都不返回),或者传递 multipliers作为引用而不是值指向它的指针——换句话说,在 C 中,使参数成为指向指针的指针。以下是第二种方法中的主要相关行:

void add(unsigned long element, unsigned long **multipliers) {

n_vector = realloc(*multipliers, sizeof(unsigned long) * size);
if (n_vector == NULL) {
… // error handling
} else {
*multipliers = n_vector;
}
}

void compute() {

add(x, &multipliers);

}

关于c - Realloc 最初有效,然后在多次重复后返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32875342/

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