我在 C 中创建一个数组列表,每次我第三次尝试重新分配数组(用于扩展它)时,都会收到以下错误消息:
malloc.c:3096: sSYSMALLOc: 断言`(old_top == (((mbinptr) (((char *) &((av)->bins[((1) - 1) * 2])) - __builtin_offsetof (struct malloc_chunk, fd)))) && old_size == 0) || ((unsigned long) (old_size) >= (unsigned long)((((__builtin_offsetof (struct malloc_chunk, fd_nextsize))+((2 * (sizeof(size_t))) - 1)) & ~((2 * (sizeof (size_t))) - 1))) && ((old_top)->size & 0x1) && ((unsigned long)old_end & pagemask) == 0)' 失败。中止
我的代码如下:
#include <stdlib.h>
#include "arraylist.h"
ARRAYLIST* newArrayList() {
ARRAYLIST* arraylist = malloc(sizeof(ARRAYLIST));
arraylist->size = 0;
arraylist->increasingStep = 2500;
arraylist->capacity = arraylist->increasingStep;
arraylist->array = calloc(sizeof(char), arraylist->increasingStep);
}
void arraylist_put(ARRAYLIST* list, char* value) {
if (list->size >= list->capacity) {
arraylist_expand(list);
}
list->array[list->size] = value;
list->size++;
}
void arraylist_expand(ARRAYLIST* list) {
list->capacity += list->increasingStep;
char** tmp = list->array;
list->array = calloc(sizeof(char), list->capacity);
int i;
for (i = 0; i < list->size; i++) {
list->array[i] = tmp[i];
}
}
void arraylist_free(ARRAYLIST* list) {
free(list);
}
和主文件:
int main(char** argv, int argc) {
ARRAYLIST* tmp = newArrayList();
int i;
for (i = 0; i < 30000; i++) {
arraylist_put(tmp, "TEST");
printf("%d\n", i);
}
printf("Capacity: %d\n", tmp->capacity);
printf("Size: %d\n", tmp->size);
arraylist_free(tmp);
}
有人知道解决方案吗?或者有类似的情况?