gpt4 book ai didi

c - Realloc : invalid next size 上的奇怪行为

转载 作者:行者123 更新时间:2023-12-04 12:21:52 25 4
gpt4 key购买 nike

<分区>

我知道还有很多其他的 realloc 问题和答案,我几乎已经阅读了所有这些问题和答案,但我仍然无法解决我的问题。

当我无意中发现我的代码有一个非常奇怪的行为时,我决定停止尝试。我引入了一行来尝试一些事情,但是虽然我没有在 main 中使用 newElems 的值,但该行改变了行为。

注释该行时,代码首先失败 realloc。包括该行在内,第一个 realloc 有效。 (它仍然在第二个上崩溃)。

对可能发生的事情有什么想法吗?

int main(int argc, char** argv) {
Pqueue q = pqueue_new(3);
Node a = {.name = "a"}, b = {.name = "b"},
c = {.name = "c"}, d = {.name = "d"};

push(& q, & a, 3);
// the next one is the strange line: as you can see, it doesn't modify q
// but commenting it out produces different behaviour
Pqueue_elem* newElems = realloc(q.elems, 4 * q.capacity * sizeof *newElems);
push(& q, & b, 5);
push(& q, & c, 4);

char s[5];
Node* n;
for (int i = 1; i <= 65; ++i) {
sprintf(s, "%d", i);
n = malloc(sizeof *n);
n->name = strdup(s);
push(& q, n, i);
}

Node* current = NULL;
while ((current = pop(& q))) {
printf("%s ", current->name);
}
return 0;
}

和推送功能:

void push(Pqueue* q, Node* item, int priority) {
if (q->size >= q->capacity) {
if (DEBUG)
fprintf(stderr, "Reallocating bigger queue from capacity %d\n",
q->capacity);
q->capacity *= 2;
Pqueue_elem* newElems = realloc(q->elems,
q->capacity * sizeof *newElems);
check(newElems, "a bigger elems array");
q->elems = newElems;
}

// append at the end, then find its correct place and move it there
int idx = ++q->size, p;
while ((p = PARENT(idx)) && priority > q->elems[p].priority) {
q->elems[idx] = q->elems[p];
idx = p;
}
// after exiting the while, idx is at the right place for the element
q->elems[idx].data = item;
q->elems[idx].priority = priority;
}

pqueue_new 函数:

Pqueue pqueue_new(unsigned int size) {
if (size < 4)
size = 4;
Pqueue* q = malloc(sizeof *q);
check(q, "a new queue.");
q->capacity = size;
q->elems = malloc(q->capacity * sizeof *(q->elems));
check(q->elems, "queue's elements");

return *q;
}

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