我目前正在学习 C,并试图扩展结构数组的可用内存量。当我尝试增加数组时,我在运行时收到以下错误
malloc.c:2852: mremap_chunk: Assertion `((size + offset) & (GLRO (dl_pagesize) - 1)) == 0' failed. Aborted.
这是导致问题的代码。
我尝试阅读 realloc 手册页和在线教程,但无法找到解决此特定情况的任何内容。
typedef struct _hash{
int times;
char word[250];
struct _hash *n;
}Hash;
int main(){
Hash* temp;
int currentMax=10;
Hash* ptr[currentMax];
for(int i=0; i<10;i++){
ptr[i]=malloc(sizeof(ptr));
strcpy(ptr[i]->word, "hello world");
ptr[i]->times=1;
ptr[i]->n=NULL;
}
temp=realloc(ptr, 3*sizeof(Hash));
}
我预计数组的大小会扩展为 3,以便稍后可以添加其他元素,但我不断收到相同的错误。
最佳答案
ptr[i]=malloc(sizeof(ptr));
您在这里分配了错误的大小。这应该是
ptr[i]=malloc(sizeof(*ptr[i]));
或者
ptr[i]=malloc(sizeof(Hash));
因此,您随后会超出缓冲区并调用未定义的行为。
您应该考虑使用 -g
编译程序(以启用调试符号),并在 valgrind
下运行它。此类错误将立即被识别。
关于c - 如何修复C中的 'mremap chunk assertion error',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54471680/