这段代码使用realloc()实现了一个可扩展的队列,这只是原始代码的一部分。
当我运行此命令时出现错误:
typedef uint32_t u32;
typedef uint64_t u64;
typedef struct _queue_t *queue_t;
struct _queue_t {
u32 *array;
u32 FirstElem;
u32 LastElem;
u32 memory_allocated;
u32 Size;
};
queue_t queue_empty() {
queue_t queue = calloc (1, sizeof (struct _queue_t));
assert(queue != NULL);
queue->array = (u32 *) calloc(16, sizeof(u32));
queue->FirstElem = 0;
queue->LastElem = 0;
queue->memory_allocated = 16*sizeof(u32);
queue->Size = 0;
return queue;
}
void increment_queue(queue_t queue) {
queue->memory_allocated += 16;
queue->array = realloc (queue->array, queue->memory_allocated);
assert(queue->array != NULL);
}
queue_t enqueue(queue_t queue, u32 vertex) {
assert(queue != NULL);
assert(queue->array != NULL);
if ((queue->memory_allocated)/sizeof(u32) == queue->Size) {
increment_queue(queue);
}
if (queue->Size == 0) {
queue->array[queue->LastElem] = vertex;
} else {
queue->LastElem += 1;
queue->array[queue->LastElem] = vertex;
}
queue->Size = queue->Size + 1;
return queue;
}
queue_t dequeue(queue_t queue) {
assert (queue != NULL);
assert (queue_size(queue) != 0);
queue->FirstElem += 1;
queue->Size -= 1;
queue->memory_allocated -= sizeof(u32);
return queue;
}
int main() {
queue_t newq = queue_empty();
for (u32 i = 0; i < 20; i++) {
enqueue(newq, i);
}
for (u32 i = 0; i < 10; i++) {
dequeue(newq);
}
for (u32 i = 0; i < 100; i++) {
enqueue(newq, i);
}
return 0;
}
错误是:
* glibc 检测到 ./mini: realloc(): 下一个大小无效: 0x0000000001782030 **
=======回溯:=========
………………
最佳答案
问题出在出队时,您减少了queue->memory_allocated
。发生的事情是这样的:您创建了一个empty_queue。您开始向数组添加元素 - 这会将大小增加 16。我们继续输入元素,直到第 16 次,然后将大小增加到 32。并使用其中的前 20 个。
此时内存中的数组用于前 20 个,然后用于后 12 个。然后我们开始调用 dequeue 并删除 10 个项目。 Size 现在等于 10,memory_alulated/u32 等于 22。您开始添加更多元素并添加 12 个元素(在数字 20 和 32 之间的 12 个可用空间中),此时 size == memory_alulated/u32 所以我们将内存分配增加 16。分配的内存现在等于 38。
内存中的数组看起来像这样: 尺寸为 22。
我们开始添加更多元素,并在其中的第 6 个元素上写入超过数组末尾。现在发生的任何事情都是公平的游戏。你的内存被破坏了,显然最终会覆盖一些重要的东西。
关于c - glibc 检测到 realloc() : invalid next size: 0x,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17182411/