Info
This question is closed. Reopen it to edit or answer.
problem in allocate and deallocating of memory in mexfunctio
1 view (last 30 days)
Show older comments
I wrote very simple program in mex but have memory error.
#include "mex.h"
void mexFunction(int nlhs,mxArray *plhs[],int nrhs,const mxArray *prhs[])
{
double *buf;
int buflen=1000;
long int index;
/* Get number of characters in the input string. Allocate enough
memory to hold the converted string. */
buf = mxMalloc(buflen);
for (index=0;index<buflen;index++)
buf[index]=0;
mexPrintf("The End of program: %s\n", buf);
mxFree(buf);
return;
}
0 Comments
Answers (1)
James Tursa
on 29 Jun 2015
Edited: James Tursa
on 29 Jun 2015
The basic problem is you don't allocate enough memory for your doubles, since mxMalloc works in bytes. So do this instead:
buf = mxMalloc(buflen * sizeof(*buf));
Also, you are attempting to print buf as a string using the %s format, i.e. a null terminated C-style string, when in fact buf is a (double *) type ... it points to doubles, not characters that have a null character at the end. If you want to print out the memory address, use %p instead. E.g.,
mexPrintf("The End of program: %p\n", buf);
0 Comments
This question is closed.
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!