c - 如何修复C中的 'mremap chunk assertion error'

标签 c

我目前正在学习 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/

相关文章:

c - 如何从 char 缓冲区创建 long int?

c++ - 从 C、C++ 在 Linux 中发出系统命令

c - Yacc/Lex 给出此代码的段错误

c - fork调用后的地址空间

c - 求和链表

c - 将一个字符串分成一定数量的子串(C)

c - 具有特定要求的纯C通用双向哈希表

c - 函数 ptrs 数组上的 realloc() 导致 SIGABRT

c - 在C中获取文件扩展名

c - malloc'ing 和 realloc'ing 指针在返回时导致内存泄漏