Categories
Programming

Invalid array pointers in C

I’ve been working with the MEX API. It basically allows you to run C/Fortran code from MATLAB. This can be very useful, since you can do some performance critical steps in C/Fortran and the rest of the code in Matlab. But often enough, when you try to combine two things with complimentary features, you end up with the worst of both worlds. This is not entirely the case for CMEX, but it does involve much more thought to implement efficient code (since MATLAB’s JIT compiler has been becoming better over time).

But back to the subject. I had recently, amongst other changes, replaced the unsigned ints for ints. The code would run fine, I could manipulate the output, plot it, mesh it, etc. However, as soon as I cleared it, I would get an ugly crash with the not-very-helpful message:

free(): invalid pointer: 0xsomememoryaddress

Oopsie! What in the world does that mean? I investigated the bug further using gdb, but the address I got from the crash message was not part of my variables. After some fussing around, I found out that the problem was that one of our ints was initialized with UINT_MAX, which is 2^{32}-1 for unsigned ints, but is -1 for signed ints (at least for x86 processors). So, it turns out I was writing to the negative indexes of one of the arrays (the exact one that would crash when cleared).

My guess is that array[-1] contains some kind of control code for the array. Maybe a pointer or identifier, so that free() knows what/how much memory to free.

An example code of the issue can be found below:

#include <stdio.h>
#include <stdlib.h>

int main()
{
        double * array = (double*) malloc(100*sizeof(double));

        printf("Array[-1] = 0\n");
        array[-1] = 0;

        printf("Freeing array\n");
        free(array);
        return 0;
}

Which outputs:

*** Error in `./negarr': free(): invalid pointer: 0x0000000000828010 ***

I hope this is helpful for someone.

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.