Use strcpy with mxArrayToString ?
3 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
PeakBragg
el 15 de Mzo. de 2023
Editada: James Tursa
el 29 de Mzo. de 2023
I am trying to make a deep copy of the string from char pointer using strcpy from standard library. But it is causing the program to crash
% test2.c
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, mxArray const *prhs[])
{
char* inputStr = mxArrayToString(prhs[0]);
char* inputStr2 = strcpy(inputStr2, inputStr); % Not working and causing matlab to crash
mexPrintf("Input: %s\n", inputStr); % Working as expected
mexPrintf("Input: %c\n", inputStr[2]);
char s = inputStr[2];
mexPrintf("Copy: %c\n", s);
mexPrintf("Copy: %s\n", inputStr2); % Not working and causing matlab to crash
}
With some testing, I can access the inputStr pointer using mxArrayToString, I can also access individual elements of the char that inputStr points to. But I can not use inputStr as pointer to perform a deep copy. My guess is it is probably due to some mechanism within mxArray class that protects itself from being manipulated in unexpected way, but couldn't figure out the details
0 comentarios
Respuesta aceptada
James Tursa
el 28 de Mzo. de 2023
Editada: James Tursa
el 29 de Mzo. de 2023
char* inputStr2 = strcpy(inputStr2, inputStr); % Not working and causing matlab to crash
This line crashes because inputStr2 is an unitialized pointer and you are attempting to copy data to whatever garbage value happens to be contained in inputStr2 as a memory location. You need to allocate memory behind inputStr2 (e.g. via mxMalloc or mxCalloc) before you can copy into where it points to. E.g., you need something like this:
#include <string.h> // include the header file that has strcpy !!!
:
char *inputStr2 = (char *)mxMalloc( some expression for the number of chars needed ); // I will let you figure this out
strcpy(inputStr2, inputStr);
This line doesn't crash because mxArrayToString has memory allocation functions built into the function:
char* inputStr = mxArrayToString(prhs[0]);
You also need to free the memory behind the pointers when you are done with them. E.g.,
mxFree(inputStr);
mxFree(inputStr2);
But this all begs the question, why do you need to copy the string into a new string at all? Why not just use inputStr directly downstream in your code?
0 comentarios
Más respuestas (0)
Ver también
Categorías
Más información sobre Write C Functions Callable from MATLAB (MEX Files) en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!