Strncpy/Strncpy_s is supported by Matlab

3 visualizaciones (últimos 30 días)
Manjuna Devi
Manjuna Devi el 14 de Jul. de 2020
Editada: James Tursa el 15 de Jul. de 2020
I am very new to Matlab currently facing an issue when I run my mex file "Matlab has encountered an internal problem and needs to close".
Our code is using strncpy/strncpy_s, any one can please confirm whether Matlab supports strncpy/strncpy_s.
Compilation is successfull without any errors but when I am running the generated .mexw64 it is throwing "Matlab has encountered an internal problem and needs to close"
Below is the sample code exact functionality is not posted as it is confidential.
#include<mex.h>
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
mexPrintf("--mexfunction---\n");
main();
return 0;
}
int main(int argc, char** argv)
{
char dst[5];
printf("argv[0]: %s\n", argv[0]);
strncpy_s(dst,5, "a long string", 5);
printf("dst: %s\n",dst);
}
Please find the attached crash dump.

Respuestas (1)

James Tursa
James Tursa el 15 de Jul. de 2020
Editada: James Tursa el 15 de Jul. de 2020
Your code has bugs. That is why it is crashing. The bugs are caused by these lines:
main(); // You call main without any arguments, and without giving the compiler a prototype
:
int main(int argc, char** argv) // The function main( ) expects two input arguments
:
printf("argv[0]: %s\n", argv[0]); // You access one of the input arguments
So, your main( ) function accesses argv[0], but there was no argv passed in. So argv points to random stack garbage values and you get a crash when you access it. Your code should look something like this instead:
#include <mex.h>
int main(int argc, char** argv); // added this prototype
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
int argc = 2; // added
char *argv[] = {"1st input","2nd input"}; // added
mexPrintf("--mexfunction---\n");
main(argc,argv); // added two arbitrary arguments
// return 0; // get rid of this line ... mexFunction( ) doesn't return anything
}
int main(int argc, char** argv)
{
char dst[5];
printf("argv[0]: %s\n", argv[0]);
strncpy_s(dst,5, "a long string", 5);
printf("dst: %s\n",dst);
return 0; // added this line ... main( ) returns an int
}
Remember, though, that strncpy_s puts a null character at the end. So if there is not room to copy the string and append the null character, you will not get the string copied.

Categorías

Más información sobre String Parsing en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by