linux - C realloc断言

标签 linux gcc realloc

不确定为什么在尝试使用 realloc 时出现以下错误:

malloc.c:2401: sysmalloc: 断言`(old_top == initial_top (av) && old_size == 0) || ((unsigned long) (old_size) >= MINSIZE && prev_inuse (old_top) && ((unsigned long) old_end & (pagesize - 1)) == 0)' 失败。 中止(核心转储)

这是代码片段

#include <stdio.h>
#include <stdint.h>

typedef struct myStruct {
  char *pt;
  Uint32 tid;
} myStruct;

#define BUCKETSIZE 1024

int main(int argc, char* args[]) 
{
  myStruct *myStructs;
  size_t nstructs = 0, maxstructs = 0;

  maxstructs = BUCKETSIZE;

  myStructs = (myStruct*)malloc(maxstructs * sizeof(myStruct));
  memset(myStructs, 0, BUCKETSIZE * sizeof(myStruct));

  for(nstructs = 0 ; nstructs < 10240 ; nstructs++)
  {
    if (nstructs > maxstructs)
    {
        size_t newsize = (maxstructs + BUCKETSIZE) * sizeof(myStruct);
        myStructs = (myStruct*)realloc(myStructs, newsize);
        memset((uint8_t*)myStructs + maxstructs * sizeof(myStruct), 0, BUCKETSIZE * sizeof(myStruct));
        maxstructs += BUCKETSIZE;
    }

    myStructs[nstructs].pt = args[0];
    myStructs[nstructs].tid = nstructs+1;
  }
  return 0;
}

最佳答案

在你的循环中,你检查了 nstructs > maxstructs,所以当 nstructs==1024maxstructs==1024 时,你不t realloc,但访问 myStructs[1024],这是最后一次。您需要在测试条件中使用 nstructs>=maxstructs

关于linux - C realloc断言,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52328141/

相关文章:

c - 为什么realloc似乎没有扩展内存。重新分配未按描述工作

c++ - 应用程序库之间循环依赖的影响

linux - Google Hangout 插件 linux ARM (armhf)

Java运行环境还是其他问题?

c - 如何编写由用户空间函数调用的内核空间函数?

c++ - 使用 _GLIBCXX_CXX11_ABI 来使用具有 C++ 11/14 功能的 pre-5.1 C++ ABI 有什么影响?

c++ - 最小 float (最接近零)

c - 如何重新分配不同大小的二维结构指针

使用 gcc 时 CLion 调试器不工作

c - 为什么它返回我段错误(核心转储)?