Use strcpy with mxArrayToString ?

3 次查看(过去 30 天)
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

采纳的回答

James Tursa
James Tursa 2023-3-28
编辑:James Tursa 2023-3-29
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 个)

类别

Help CenterFile Exchange 中查找有关 Write C Functions Callable from MATLAB (MEX Files) 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by