Search code examples
cmatlabmallocmexs-function

Error using malloc inside SFunction


I´m developing a C-MEX SFunction to integrate with simulink. The objective here is to convert an array of ascii codes do double. Before opening matlab, I implemented a test code using Visual Studio and it works just fine. (see below)

#include "stdafx.h"
#include "stdlib.h"
#include <stdio.h>
#include <math.h>
#include <string.h>

int _tmain(int argc, _TCHAR* argv[])
{
    double finalDouble;
    size_t len = 1;
    char* concatenation;
    double character2 = 54; // 6 in ascii
    double character1 = 46; // dot in ascii
    double character0 = 51; // 3 in ascii

    int character2_int = (int)(character2);
    int character1_int = (int)(character1);
    int character0_int = (int)(character0);

    char buffer2[1];
    char buffer1[1];
    char buffer0[1];

    sprintf(buffer2,"%c",character2_int);
    sprintf(buffer1,"%c",character1_int);
    sprintf(buffer0,"%c",character0_int);

    concatenation = (char*)malloc(len+len+len);
    strcpy(concatenation, buffer2); /* copy into the new var */
    strcat(concatenation, buffer1); /* concatenate */
    strcat(concatenation, buffer0); /* concatenate */

    finalDouble = atof(concatenation); // final double must be 6.3

    //y0[0] = finalDouble;
}

After everything was tested in VisualStudio, I copied to SFunction Builder in matlab. It do not crashes, but looks like malloc is not working as expected. The expected output is 6.3 (double), but I get only the last digit 3 (double)

Does anyone know whats happening? Any advices?

enter image description here


Solution

  • You are using sprintf on a one byte buffer whereas your buffer should have at least a size of 2. And you don't allocate enough memory with malloc. This leads to undefined behaviour.

    Change :

    char buffer2[1];
    char buffer1[1];
    char buffer0[1];
    ...
    concatenation = (char*)malloc(len+len+len);
    

    to

    char buffer2[2];
    char buffer1[2];
    char buffer0[2];
    ...
    concatenation = (char*)malloc(len+len+len+1);
    

    Your code is very odd and complicated for such an easy task. What exactly are you trying to achieve ?