我知道还有其他realloc问题和答案吨,我几乎读了所有这些,但我仍然无法解决我的问题。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;
}
你删除的“不相关部分”可能是最相关的:我认为这是你写入'newElems'的东西,对吗? – dasblinkenlight
是的,没有。 我不使用newElements,如果只有q-> elems(已分配给newElems)。我将包括它 –
@CiprianTomoiaga如果你写入'newElems'或者'q-> elems'指向的块,它就是同一个块。错误可能在那里。使用valdrind更快地找到它。 – dasblinkenlight