我正在尝试在C中创建一个动态数组来实现队列,当我编译时,我得到以下错误: * glibc检测到 。 / Ex:realloc():下一个大小无效:0x0000000001fbe030 * *
我的代码如下:
typedef uint32_t u32;
typedef uint64_t u64;
typedef struct _queue_t *queue_t;
struct _queue_t {
u32 *array; // Arreglo para guardar elementos de la cola
u32 FirstElem; // Primer elemento de la cola
u32 LastElem; // Ultimo elemento de la cola
u32 memory_allocated; // Para saber si tengo que pedir mas memoria
u32 Size; // Devuelve la cantidad actual de elementos que tiene la cola
};
queue_t queue_empty() {
queue_t queue = NULL;
queue = calloc (1, sizeof (struct _queue_t));
assert(queue != NULL);
queue->array = (u32 *) calloc(100, sizeof(u32));
queue->FirstElem = 0;
queue->LastElem = 0;
queue->memory_allocated = 100;
queue->Size = 0;
return queue;
}
int main() {
queue_t queue = NULL;
queue = queue_empty();
for (u32 i = 0; i < 1000; i++) {
if (queue->memory_allocated == queue->Size) {
queue->array = (u32 *) realloc (queue->array, 100*sizeof(u32));
queue->memory_allocated += 100;
}
queue->LastElem += 1;
queue->array[queue->LastElem] = i;
queue->Size += 1;
}
return(0);
}
为什么会出现此错误?
答案 0 :(得分:2)
您总是在此处分配相同大小的内存:
if (queue->memory_allocated == queue->Size) {
queue->array = (u32 *) realloc(
queue->array, 100*sizeof(u32)); // always 100 * sizeof(u32)
queue->memory_allocated += 100;
}
我认为你想要做的就是多分配100个元素。你还应该通过引入一个临时存储来检查realloc()的返回值,因为可能会返回NULL
,导致丢失指向当前分配的内存的唯一指针:
if (queue->memory_allocated == queue->Size) {
int new_size = queue->memory_allocated + 100; // increment first
u32* new_array = (u32 *) realloc(queue->array, new_size * sizeof(u32));
if (new_array) { // update only if realloc() returns a valid address.
queue->memory_allocated = new_size;
queue->array = new_array;
} else {
// do something in react
}
}