我有以下代码:
int Class::set(const char * id_tran_typ_)
{
char *trimmed_id_tran_typ_ = NULL;
trimString(id_tran_typ_, &trimmed_id_tran_typ_);
int len = strlen(trimmed_id_tran_typ_);
if (len < 1)
_id_tran_typ = DEFAULT_STRING;
else
_id_tran_typ = id_tran_typ_;
delete[] trimmed_id_tran_typ_;
trimmed_id_tran_typ_ = NULL;
return SUCCESS;
}
在这里,我在 int 处获得了 SEGV 信号len = strlen(trimmed_id_tran_typ_);
trimString 函数是这样的:
char *trimString(const char *sP_, char **dP_)
{
*dP_ = NULL;
if (sP_ == NULL)
return *dP_;
const char *lastPos = (char *)&sP_[strlen(sP_)];
const char *startPos = (char *)sP_;
const char *endPos = lastPos;
int len = strlen(sP_);
for (; endPos != sP_; endPos--)
{
if (*(endPos - 1) != ' ')
{
len = endPos - sP_; // *endPos = '\0';
break;
}
}
if (len == 0) // if (*endPos != '\0')
{
*dP_ = new char[1];
*dP_[0] = '\0';
return *dP_;
}
for(; startPos < endPos; startPos++, len--)
{
if (*startPos != ' ')
break;
}
if (startPos == endPos)
{
*dP_ = new char[1];
*dP_[0] = '\0';
return *dP_;
}
*dP_ = STRDUP(startPos, len);
return *dP_;
}
现在我的问题很明显,为什么我在这里遇到分段错误。
是因为我没有收到set()
函数发送的函数中的字符串trimString()
吗?
这是看起来的STRDUP()
样子:
char *STRDUP(const char *sP_, const int len_)
{
if (! sP_)
return NULL;
else if (len_ < 1)
return NULL;
char *newP = new char [ len_ + 1] ;
memset(newP, '\0', len_+1);
strncpy(newP, sP_, len_);
return(newP);
}