Use strcpy with mxArrayToString ?

3 Ansichten (letzte 30 Tage)
PeakBragg
PeakBragg am 15 Mär. 2023
Bearbeitet: James Tursa am 29 Mär. 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

Akzeptierte Antwort

James Tursa
James Tursa am 28 Mär. 2023
Bearbeitet: James Tursa am 29 Mär. 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?

Weitere Antworten (0)

Kategorien

Mehr zu Write C Functions Callable from MATLAB (MEX Files) finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by