Skip to content
Advertisement

C realloc assertion

Not sure why I’m getting the following error when trying to use 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)’ failed. Aborted (core dumped)

Here is the code fragment

#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;
}

Advertisement

Answer

In your loop, you check for nstructs > maxstructs, so when nstructs==1024 and maxstructs==1024, you don’t realloc, but access myStructs[1024], which is one past the end. You would need nstructs>=maxstructs in your test condition.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement