From: Clement on
Hello,

I am using a C mex file to use a C program which extract data from a file and write it in .txt file. This .txt file is then used with dlmread to get data in matrix.

I can use my function one time, but the next call to it or a simply command like "clear all" cause a segmentation fault and Matlab ending. I think this error is from a problem in memory management, but I do not understand how it works with mex files...

My C mex file is:

/*******************************************************************************
#include "mex.h"
#include "matrix.h"
#include <string.h>
#include <stdio.h>

#define MAX_CHAR_PER_LINE 10000

void createTXT(char *nomFichierIn);

/*******************************************************************************
Fonction principale
*******************************************************************************/

void createTXT(char *kml_filename)
{
char separateur = ',';
char matlab_filename[600];
char line[MAX_CHAR_PER_LINE];
char coords[60];

char *temp;

int flag_Placemark = 0;
int flag_coordinates = 0;

FILE *p_kml_fileIn;
FILE *p_matlab_fileOut;

p_kml_fileIn = NULL;
p_matlab_fileOut = NULL;

memset(line,0,sizeof(line));
memset(coords,0,sizeof(coords));
memset(matlab_filename,0,sizeof(matlab_filename));

printf("Debut creation fichier Matlab\n");

// Ouverture du fichier source
p_kml_fileIn = fopen(kml_filename,"r");

if(p_kml_fileIn == NULL) {
printf("[ERREUR] Fichier non ouvert : %s\n",kml_filename);
return;
}

// Ouverture du fichier de sortie
strncpy(matlab_filename,kml_filename,strlen(kml_filename)-4); // copie du nom du source sans extension
strcat(matlab_filename,"_matlab.txt");
p_matlab_fileOut = fopen(matlab_filename,"w");
printf("Fichier kml source: %s\n",kml_filename);
printf("Fichier Matlab cree: %s\n",matlab_filename);

if(p_matlab_fileOut == NULL) {
printf("[ERREUR] Fichier non ouvert : %s\n",matlab_filename);
return;
}
else {
// Lecture du fichier d'entrée
while(fgets(line,sizeof(line),p_kml_fileIn) != NULL) {
// Si une balise Placemark puis une balise coordinates ont été trouvées
if(flag_coordinates == 1) {
// Traiter les points
while( strcmp(line,"</coordinates>") < 0) {
// Rechercher le début des coordonnées suivantes
temp = strchr(line,' ');
if(temp != NULL) {
// Copier les coordonnées
strncpy(coords,line,strlen(line)-strlen(temp));
fprintf(p_matlab_fileOut,"%s\n",coords);

// Copie du reste de la ligne, sans le caractère espace en tête de temp
temp++;
strcpy(line,temp);
temp = NULL;

// Réinitialisation des coordonnées
memset(coords,0,sizeof(coords));
}
}
flag_coordinates = 0;
}
// Affichage de la ligne lue
//printf("line: %s\n",line);

// Test si la balise présente dans la chaîne est <Placemark>
if(strstr(line,"<Placemark>") != NULL)
{
//printf("<Placemark> found\n");
flag_Placemark = 1;
}

if (flag_Placemark == 1)
{
if(strstr(line,"<coordinates>") != NULL)
{
//printf("<coordinates> found\n");
flag_coordinates = 1;
}
}
// Réinitialisation de line
memset(line,0,sizeof(line));
}
}
// Fermeture des fichiers source et de sortie
fclose(p_kml_fileIn);
fclose(p_matlab_fileOut);

printf("Fin creation fichier Matlab\n");
}

/*******************************************************************************
Fonction gateway
*******************************************************************************/
/* The gateway function */
void mexFunction( int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
char *kml_filename;

/* check for proper number of arguments */
if(nrhs!=1) {
mexErrMsgIdAndTxt("MyToolbox:arrayProduct:nrhs",
"One input required.");
}

/* make sure the first input argument is string */
if( !mxIsChar(prhs[0]) ) {
mexErrMsgIdAndTxt("MyToolbox:arrayProduct:notScalar",
"Input argument must be a string.");
}

/* get the input string */
mxGetString(prhs[0],kml_filename,mxGetN(prhs[0])+1);

/* call the computational routine */
createTXT(kml_filename);

}


I have the following informations about the error:

MATLAB crash file:C:\DOCUME~1\GT050738\LOCALS~1\Temp\matlab_crash_dump.3712
------------------------------------------------------------------------
Segmentation violation detected at Thu Jan 28 10:49:30 2010
------------------------------------------------------------------------

Configuration:
MATLAB Version: 7.9.0.529 (R2009b)
MATLAB License: DEMO
Operating System: Microsoft Windows XP
Window System: Version 5.1 (Build 2600: Service Pack 2)
Processor ID: x86 Family 6 Model 6 Stepping 1, GenuineIntel
Virtual Machine: Java 1.6.0_12-b04 with Sun Microsystems Inc. Java HotSpot(TM) Client VM mixed mode
Default Encoding: windows-1252

Fault Count: 1

Register State:
EAX = 6a617254 EBX = 00000000
ECX = 465f7465 EDX = 01040608
ESI = 0f0b2d20 EDI = 01040000
EBP = 00c3e294 ESP = 00c3e1d8
EIP = 7c9394e7 FLG = 00010213

Stack Trace:
[0] ntdll.dll:0x7c9394e7(0x01040000, 0, 0x0f0b2d40, 0x043102e8)
[1] MSVCR80.dll:0x78134c39(0x0f0b2d40, 0x7baeed50, 0x0f0b2d40, 0x7bb7b2b0)
[2] libut.dll:_utFree(0x0f0b2d40, 31, 0x211af228, 0x0f0b2d40) + 92 bytes
[3] m_interpreter.dll:public: virtual void * __thiscall accelCode::`scalar deleting destructor'(unsigned int)(1, 31, 0x211af228, 0) + 71 bytes
[4] m_interpreter.dll:public: void __thiscall _jitSegInfo::Clear(void)(0x0f0e1608, 0x0f0e16b8, 0, 0x0f18f1a0 "??$Log(a)MM@mu@@YAIPAM0IIIPA_N@Z") + 239 bytes
[5] m_interpreter.dll:void __cdecl inFreeJitSegInfo(class _jitSegInfo * *,bool)(0x211ae558, 1, 0x211762e0 "¤Ä»z", 0x0f0e2d30) + 153 bytes
[6] m_interpreter.dll:public: void __thiscall Mfh_mp::inFreeMfunctionData(void)(0x211762ff, 0x211762e0 "¤Ä»z", 0x0253b038, 0x211762e0 "¤Ä»z") + 461 bytes
[7] m_interpreter.dll:public: virtual void __thiscall Mlm_mp::unload_file(void)(0x211762ff, 0x211762e0 "¤Ä»z", 0x7a151924, 0x0253aa70) + 128 bytes
[8] m_dispatcher.dll:public: virtual void __thiscall Mlm_file::unload_mf(void)(0x0f190fbc, 0, 0, 1) + 11 bytes
[9] m_dispatcher.dll:??$clear(a)VMlmmf_named_matcher@@@@YAXVMlmmf_named_matcher@@H@Z(0x7bf5ef00, 0x0f190fbc, 6, 0) + 77 bytes
[10] m_dispatcher.dll:_mdClearFunctionsByName(0, 0, 0x7a8eb655, 0x0f190fbc) + 372 bytes
[11] m_interpreter.dll:void __cdecl inClearAllFcns(void)(0xffffffff, 0x0d06d220, 0, 0x009201db) + 9 bytes
[12] m_interpreter.dll:public: virtual void __thiscall InterpBridge::FullClearFcn(int,struct mxArray_tag * *,int,struct mxArray_tag * * const)(0, 0x00c3ef1c, 1, 0x00c3ef7c) + 462 bytes
[13] m_interpreter.dll:void __cdecl inFullClearFcn(int,struct mxArray_tag * * const,int,struct mxArray_tag * * const)(0, 0x00c3ef1c, 1, 0x00c3ef7c) + 69 bytes
[14] m_dispatcher.dll:public: virtual void __thiscall Mfh_builtin::dispatch_mf(int,struct mxArray_tag * *,int,struct mxArray_tag * *)(0, 0x00c3ef1c, 1, 0x00c3ef7c) + 92 bytes
[15] m_dispatcher.dll:public: virtual void __thiscall Mfh_MATLAB_fn::dispatch_fh(int,struct mxArray_tag * *,int,struct mxArray_tag * *)(0, 0x00c3ef1c, 1, 0x00c3ef7c) + 193 bytes
[16] m_interpreter.dll:int __cdecl inDispatchFromStack(int,char const *,int,int)(313, 0x211a8efc "clear", 0, 1) + 623 bytes
[17] m_interpreter.dll:int __cdecl inInterp(enum inDebugCheck,int,int,enum opcodes,struct inPcodeNest_tag volatile *,int *)(1, 0, 1, 0) + 1295 bytes
[18] m_interpreter.dll:int __cdecl protected_inInterp(enum inDebugCheck,int,int,enum opcodes,struct inPcodeNest_tag *,int *)(1, 0, 1, 0) + 39 bytes
[19] m_interpreter.dll:int __cdecl inInterPcodeSJ(enum inDebugCheck,int,int,enum opcodes,struct inPcodeNest_tag *,int *)(1, 0, 1, 0) + 251 bytes
[20] m_interpreter.dll:int __cdecl inExecuteMFunctionOrScript(class Mfh_mp *,bool)(0x01040001, 0xffffffff, 0x0f0e39a8, 0) + 924 bytes
[21] m_interpreter.dll:void __cdecl inRunMfile(int,struct mxArray_tag * *,int,struct mxArray_tag * *,class Mfh_mp *,struct inWorkSpace_tag *)(0, 0x00c3f988, 0, 0) + 466 bytes
[22] m_interpreter.dll:public: virtual void __thiscall Mfh_mp::dispatch_file(struct _mdUnknown_workspace *,int,struct mxArray_tag * *,int,struct mxArray_tag * *)(0, 0, 0x00c3f988, 0) + 23 bytes
[23] m_interpreter.dll:public: virtual void __thiscall Mfh_mp::dispatch_file(int,struct mxArray_tag * *,int,struct mxArray_tag * *)(0, 0x00c3f988, 0, 0) + 25 bytes
[24] m_dispatcher.dll:public: virtual void __thiscall Mfh_file::dispatch_fh(int,struct mxArray_tag * *,int,struct mxArray_tag * *)(0, 0x00c3f988, 0, 0) + 204 bytes
[25] m_interpreter.dll:void __cdecl inEvalPcodeHeaderToWord(struct _memory_context *,int,struct mxArray_tag * * const,struct _pcodeheader *,class Mfh_mp *,unsigned long)(0x7bb796d4, 0, 0x00c3f988, 0x00c3f898) + 73 bytes
[26] m_interpreter.dll:enum inExecutionStatus __cdecl in_local_call_script_function(struct _memory_context *,struct _pcodeheader *,int,struct mxArray_tag * * const,unsigned long,bool)(0x7bb796d4, 0x00c3f898, 0, 0x00c3f988) + 70 bytes
[27] m_interpreter.dll:__catch$??1inProtectHotSegment@@QAE(a)XZ$0(0x7bb796d4, 0x022f6028 "clear all\n", 0, 0) + 888 bytes
[28] m_interpreter.dll:enum inExecutionStatus __cdecl inEvalCmdWithLocalReturn(char const *,int *,bool,bool,bool (__cdecl*)(void *,char const *))(0x022f6028 "clear all\n", 0, 0, 1) + 80 bytes
[29] m_interpreter.dll:public: virtual enum inExecutionStatus __thiscall InterpBridge::EvalCmdWithLocalReturn(char const *,int *,bool,bool)(0x022f6028 "clear all\n", 0, 0, 1) + 25 bytes
[30] m_interpreter.dll:_inEvalCmdWithLocalReturn(0x022f6028 "clear all\n", 0, 0, 1) + 30 bytes
[31] bridge.dll:enum inExecutionStatus __cdecl evalCommandWithLongjmpSafety(char const *)(0x022f6028 "clear all\n", 0, 0x0eeea3d0, 0) + 67 bytes
[32] bridge.dll:__catch$_mnParser$0(0x024faf78, 0, 0x746a0e01, 1) + 300 bytes
[33] mcr.dll:private: void __thiscall mcrInstance::mnParser_on_interpreter_thread(void)(0x0eeea408, 0x7ffdd000 "¤ÝÃ", 0x00c3fb3c, 0x7e39f7f6) + 51 bytes
[34] mcr.dll:public: void __thiscall boost::function0<void>::operator()(void)const (0, 0x0eeea3d0, 0, 0x0eeea3d0) + 63 bytes
[35] mcr.dll:public: virtual void __thiscall mcr::runtime::InterpreterThread::Impl::NoResultInvocationRequest::run(void)(0x7a27a800, 0x7c91e473, 0x00c3fb70, 48) + 53 bytes
[36] mcr.dll:private: static void __cdecl mcr::runtime::InterpreterThread::Impl::invocation_request_handler(int)(0x0eeea3d0, 0, 0x00030000 "Actx ", 0x00c3fcb4) + 40 bytes
[37] uiw.dll:bool __cdecl UIW_DispatchUserMessage(int,int)(9225, 0x0eeea3d0, 0x00c3fcb4, 2) + 81 bytes
[38] uiw.dll:long __stdcall HandleUserMsgHook(int,unsigned int,long)(0, 1, 0x00c3fcb4, 0x79c73540) + 95 bytes
[39] USER32.dll:0x7e3b18e3(0x00030000 "Actx ", 1, 0x00c3fcb4, 0x7b38edd0)
[40] USER32.dll:0x7e39f7f6(0x00c3fca4, 0x00c3fcb4, 0x00c3fcd0, 0)
[41] USER32.dll:0x7e39f94b(0x00c3fca4, 48, 0x00030000 "Actx ", 1)
[42] ntdll.dll:0x7c91e473(0x00c3fd20, 0, 0, 0)
[43] uiw.dll:void __cdecl UIW_GetAndDispatchMessage(struct tagMSG *)(0x00c3fd20, 2, 2, 0x0eeea3d0) + 20 bytes
[44] uiw.dll:void __cdecl UIW_GetAndDispatchMessage(void)(0x024cd8f0, 0, 0x02530920, 0) + 15 bytes
[45] uiw.dll:void __cdecl ws_ProcessPendingEventsMainLoop(int,bool)(1, 0, 0x00c3fdbc "üýÃ", 0x7a27d26a) + 356 bytes
[46] uiw.dll:void __cdecl ws_ProcessPendingEvents(int,int)(1, 0xffffffff, 0x024cd8f0, 0x02530920) + 14 bytes
[47] mcr.dll:public: void __thiscall mcr::runtime::InterpreterThread::Impl::process_events(class boost::shared_ptr<class mcr::runtime::InterpreterThread::Impl> const &)(0x00c3fe14, 2, 0x02530320, 0x02f1dd8c) + 138 bytes
[48] mcr.dll:__catch$?run(a)Impl@InterpreterThread(a)runtime@mcr@@QAEKABV?$shared_ptr(a)VImpl@InterpreterThread(a)runtime@mcr@@@boost@@PAUinit_context(a)1234@@Z$0(0x00c3fe14, 0x02532eb0, 0x7a27d630, 0x0252c310) + 128 bytes
[49] mcr.dll:unsigned long __cdecl run_init_and_handle_events(void *)(0x02f1dd8c, 0, 0x02530290, 0) + 76 bytes
[50] mcr.dll:private: void __thiscall mcr::runtime::InterpreterThreadFactory::runThreadFunction(void)(0x00c3fec8, 0x00c3fe80, 0x00c3fe84 "ðþÃ", 0x7bafb34c) + 108 bytes
[51] MATLAB.exe:public: void __thiscall boost::function0<void>::operator()(void)const (336702, 0x0040b7f4, 0, 0x78131731) + 63 bytes
[52] MATLAB.exe:int __cdecl mcrMain(int,char const * * const)(1, 0x0252c6e0, 4194304, 10) + 230 bytes
[53] MATLAB.exe:_WinMain(a)16(4194304, 0, 336702, 10) + 75 bytes
[54] MATLAB.exe:___tmainCRTStartup(0, 0, 0x7ffde000, 0x8054abb8) + 320 bytes
[55] kernel32.dll:0x7c816fe7(0x00406faa, 0, 0x00905a4d, 3)

Please follow these steps to report this problem to The MathWorks so we
have the best chance of correcting it:

The next time MATLAB is launched under typical usage, a dialog box will
open to help you send the error log to The MathWorks. Alternatively, you
can send an e-mail to segv(a)mathworks.com with the following file attached:
C:\DOCUME~1\GT050738\LOCALS~1\Temp\matlab_crash_dump.3712

If the problem is reproducible, please submit a Service Request via:
http://www.mathworks.com/support/contact_us/ts/help_request_1.html

A technical support engineer might contact you with further information.

Thank you for your help. MATLAB may attempt to recover, but even if recovery appears successful,
we recommend that you save your workspace and restart MATLAB as soon as possible.


I will really appreciate any help or suggestion to solve this problem.
From: Rune Allnor on
On 28 Jan, 11:30, "Clement " <keke...(a)orange.fr> wrote:
> Hello,
>
> I am using a C mex file to use a C program which extract data from a file and write it in .txt file. This .txt file is then used with dlmread to get data in matrix.
>
> I can use my function one time, but the next call to it or a simply command like "clear all" cause a segmentation fault and Matlab ending. I think this error is from a problem in memory management, but I do not understand how it works with mex files...

The cause of the problem is that you do not know how
to program C. I commented on a similar case a couple
of days ago:

http://groups.google.no/group/comp.soft-sys.matlab/msg/73eba4daa565a3a0?hl=no

Either take your time (and preferably a class) to learn
how to program C (and learn it well), or be prepared to
spend 90% of your time tracking down these kinds of bugs.

Rune
From: Praetorian on
> /*******************************************************************************
>   Fonction gateway
> *******************************************************************************/
> /* The gateway function */
> void mexFunction( int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
> {
>     char *kml_filename;
>
> ......
>
>     /* get the input string */
>     mxGetString(prhs[0],kml_filename,mxGetN(prhs[0])+1);
>
>     .......
> }
>

Clement,
The problem is with the mxGetString() call, the second parameter is
expected to be a pointer to an array of chars, not just a pointer.
Likewise, the third parameter should be the length of this array of
chars, not the length of the MATLAB string. Read the documentation for
mxGetString(), there are links to files containing example code. Also
take a look at mxArrayToString(), but remember to call mxFree() if you
plan to use mxArrayToString().

HTH,
Ashish.
From: Clement on
Praetorian,

the problem was actually with mxGetString, I did not allocate memory for my input filename argument. I check the exemple as you advise me, the corrected mexFunction is here, now it works as I expected and no more error occurs. Thank you for help me to fix this problem.

Clement.

void mexFunction( int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
char *kml_filename;
mwSize kml_filename_len;
int status;

/* check for proper number of arguments */
if(nrhs!=1) {
mexErrMsgIdAndTxt("MyToolbox:arrayProduct:nrhs",
"One input required.");
}

/* make sure the first input argument is string */
if( !mxIsChar(prhs[0]) || (mxGetM(prhs[0]) != 1 )) {
mexErrMsgIdAndTxt("MyToolbox:arrayProduct:notScalar",
"Input argument must be a string.");
}

/* get the input string */
kml_filename_len = mxGetN(prhs[0])*sizeof(mxChar)+1;
kml_filename = mxMalloc(kml_filename_len);

/* Copy the string data into kml_filename. */
status = mxGetString(prhs[0], kml_filename, kml_filename_len);
mexPrintf("Input file: %s\n", kml_filename);

/* call the computational routine */
createTXT(kml_filename);

/* When finished using the string, deallocate it. */
mxFree(kml_filename);
}