Fred Alcove
Fred Alcove

Reputation: 53

Mex function crashes upon completion

I have a C mex file here that executes properly, but crashes MATLAB with a segfault after it's done executing. Since it's crashing after the program has finished executing, it makes me think that MATLAB's auto-freeing of allocated memory is causing the issue. However, I free my own dynamically allocated variables and do not attempt to free mxArray structures. Please have a look and see if you can help me determine why it's causing MATLAB to crash.

#include <mex.h>
#include <matrix.h>
#include <stdio.h>

void mexFunction(
int nlhs, mxArray *plhs[],
int nrhs, const mxArray *prhs[])
{ 
    /* Declare variables. */
    int i ,j, numdims, *ipos, count;
    const mwSize *dim_array;
    mwSize size;
    double *pos, rad;

    /* Ingest inputs. */
    numdims = mxGetNumberOfDimensions(prhs[0]);
    dim_array = mxGetDimensions(prhs[0]);
    rad = mxGetScalar(prhs[1]);
    pos = mxGetData(prhs[0]);
    size = dim_array[0]*dim_array[1];

    ipos = (int*) mxMalloc(size);
    for (i = 0; i < size; i++)
        ipos[i] = (int) (pos[i]*rad);
    count = 0;
    for (i = 0; i < size; i+=2)
        for (j = i + 2; j < size; j+=2)
            if (ipos[i] == ipos[j])
                if (ipos[i+1] == ipos[j+1])
                    count++;
    mxFree(ipos);

    /* Generate output */
    plhs[0] = mxCreateDoubleScalar(count);
    printf("\nProgram finished executing!\n");
}

Thanks in advance for any help!

Edit: I should also note that the inputs to the program are intended to be (in order) a 2 x n matrix and a scalar, where n can be any positive integer. The actual program checks the dimensions correctly, but I did not include those lines here to save codespace.

Upvotes: 4

Views: 1011

Answers (2)

Fred Alcove
Fred Alcove

Reputation: 53

After having written a couple hundred C programs with dynamic memory allocation, I'm a little bit ashamed to say that the mistake was this:

Replace

    ipos = (int*) mxMalloc(size);

with

    ipos = (int*) mxMalloc(size*sizeof(int));

It seems that it's always the silliest of blunders that evade me. I'd like to thank everybody who might have taken a minute or two to look at the post.

Upvotes: 1

Dimochka
Dimochka

Reputation: 301

UPD. You are right - when matrix gets bigger, it crashes :)

So I think I've got an idea:

try changing your two lines of code

plhs[0] = mxCreateDoubleMatrix(1, 1, mxREAL);
mxGetPr(plhs[0])[0] = (double) count;

for a new single line

plhs[0] = mxCreateDoubleScalar(count);

It doesn't crash anymore after I've done that.

Upvotes: 2

Related Questions