此代码使用 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 * *
======= 回溯:======== ..... ............