I keep getting a SIGSEGV
crash converting a std::string
to char*
. I have a name I wish to display in an ITextControl (WDL Framework). The following snippet works fine in some parts of my app but not here:
char * paramName = new char[name.size() + 1];
std::copy(name.begin(), name.end(), paramName);
paramName[name.size()] = '\0'; // don't forget the terminating 0
lcdToWriteParamNamesTo->SetTextFromPlug(paramName);
Following the trace....
void ITextControl::SetTextFromPlug(char* str)
{
if (strcmp(mStr.Get(), str))
{
SetDirty(false);
mStr.Set(str);
}
}
Next step:
char *Get()
{
if (m_hb.GetSize()) return (char *)m_hb.Get();
static char c; c=0; return &c; // don't return "", in case it gets written to.
}
And finally CRASH!:
int GetSize() const { return m_size; }
EDIT: As requested:
void WDL_STRING_FUNCPREFIX Set(const char *str, int maxlen WDL_STRING_DEFPARM(0))
{
int s=0;
if (str)
{
if (maxlen>0) while (s < maxlen && str[s]) s++;
else s=(int)strlen(str);
}
__doSet(0,str,s,0);
}
From my limited understanding of C++ and this answer, a bounds issue could cause the SIGSEGV or writing into read-only memory.
Just to clarify, this snippet in one class ALWAYS crashes and in another class NEVER crashes, though both classes are passed the same string and ITextControl.
Can anybody help me shed some light on this?
EDIT: Suggestion to use c_str() doesn't help:
char * cstr = new char [name.length()+1];
std::strcpy (cstr, name.c_str());
lcdToWriteParamNamesTo->SetTextFromPlug(cstr);
delete[] cstr;
This also crashes.