6

I am getting a mysterious error and I have no idea why. This code runs several times before failing, and it always fails at the same point.

Here is my code:

    assert(size > 0);
    int* sorted = malloc(size * sizeof(int));

And here is the error I am getting when I run it:

    malloc.c:2369: sysmalloc: Assertion `(old_top == (((mbinptr) (((char *) &((av)->bins[((1) - 1) * 2])) - __builtin_offsetof (struct malloc_chunk, fd)))) && old_size == 0) || ((unsigned long) (old_size) >= (unsigned long)((((__builtin_offsetof (struct malloc_chunk, fd_nextsize))+((2 * (sizeof(size_t))) - 1)) & ~((2 * (sizeof(size_t))) - 1))) && ((old_top)->size & 0x1) && ((unsigned long)old_end & pagemask) == 0)' failed.

I have tried printing out size and it is 1 in this case. This code runs several times with varying values of size, including 1, before failing.

Does anyone have any idea what I am doing wrong?

Thanks.

Ian
  • 348
  • 1
  • 2
  • 11
  • possible duplicate of [Why do I get a C malloc assertion failure?](http://stackoverflow.com/questions/2987207/why-do-i-get-a-c-malloc-assertion-failure) – Ramchandra Apte Oct 20 '13 at 11:06
  • 2
    @ouah I think that line is part of the malloc function itself, rather than part of the poster's code; he probably doesn't have the source to that library. – mah Oct 20 '13 at 11:24
  • @mah right, I didn't notice it was `malloc:2369`, I thought it was in his source code. – ouah Oct 20 '13 at 12:22

1 Answers1

6

This usually happens when your code freed an invalid address at some prior time, or wrote past the end of the allocated memory block. Run your code through valgrind or some other memory profiler to see the point where this happens.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • I tried commenting out every time I used free. I still get the error. – Ian Oct 20 '13 at 11:10
  • @Ian Then look for places where you allocate memory, and see if you always provide the correct `sizeof`, and also that the indexes into that memory are correct. This is the nastiest kind of errors, it's extremely hard to find them without a memory profiler. – Sergey Kalinichenko Oct 20 '13 at 11:12
  • 1
    I tried running the code through valgrind and I found some mistakes. I will try fixing them to see if the error goes away. Thanks! – Ian Oct 20 '13 at 11:13
  • 1
    That was it! I was reading outside of memory which caused me to later write outside of memory. – Ian Oct 20 '13 at 11:27