Use strcpy with mxArrayToString ?

1 view (last 30 days)
PeakBragg
PeakBragg on 15 Mar 2023
Edited: James Tursa on 29 Mar 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

Accepted Answer

James Tursa
James Tursa on 28 Mar 2023
Edited: James Tursa on 29 Mar 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?

More Answers (0)

Categories

Find more on Write C Functions Callable from MATLAB (MEX Files) in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!