不确定为什么在尝试使用realloc时会出现以下错误:
malloc.c:2401:sysmalloc:Assertion`(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时,您不会realloc,而是访问myStructs[1024],这是一个过去的结尾。在测试条件下,您需要nstructs>=maxstructs

09-06 11:28