C++ 获取字符串长度时的SEGV信号
我有以下代码:C++ 获取字符串长度时的SEGV信号,c++,string,segmentation-fault,C++,String,Segmentation Fault,我有以下代码: 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_t
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;
}
现在我的问题很明显,为什么我在这里会出现分割错误
是不是因为我没有收到trimString()
函数发送的set()
函数中的字符串
这就是
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);
}
char*STRDUP(const char*sP_,const int len_)
{
如果(!sP_)
返回NULL;
else if(长度<1)
返回NULL;
char*newP=newchar[len_+1];
memset(newP,'\0',len_+1);
strncpy(新项目、sP_、len_);
返回(newP);
}
您的STRDUP
函数返回空指针,或者id\u tran\u typ
是空指针。最可能的解释是调用Class::set
方法时将id\u tran\u type
设置为null
。在检查长度之前,您可以通过检查trimmed\u id\u tran\u typ\u
值是否为NULL
来解决此问题
int Class::set(const char * id_tran_typ_)
{
char *trimmed_id_tran_typ_ = NULL;
trimString(id_tran_typ_, &trimmed_id_tran_typ_);
if (!trimmed_id_tran_typ_ || strlen(trimmed_id_tran_typ_) < 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类::set(const char*id\u tran\u typ)
{
char*trimmed\u id\u tran\u typ\u=NULL;
trimString(id\u tran\u typ\u和trimmed\u id\u tran\u typ\u);
如果(!trimmed_id_tran_typ_124; | strlen(trimmed_id_tran_typ)<1)
_id\u tran\u typ=默认字符串;
其他的
_id_tran_typ=id_tran_typ;
删除[]已修剪的\u id\u tran\u typ\u;
修剪的\u id\u传输类型\u=空;
回归成功;
}
您遗漏了最重要的部分:STRDUP
。除了前面提到的STRDUP
之外,您如何调用set
?set()的调用如何与分段错误联系在一起?您执行了哪些调试?所有这些代码是否直接导致SEG故障?我对此表示怀疑。实际上,这个set()
函数是从类的构造函数中调用的。基本上,类
对象被推到队列中。第一个物体被推得很好。但正是第二个问题引起了所有的痛苦。构造函数在某处被这样调用Sample=newclass()代码>这就是STRDUP函数的外观
int Class::set(const char * id_tran_typ_)
{
char *trimmed_id_tran_typ_ = NULL;
trimString(id_tran_typ_, &trimmed_id_tran_typ_);
if (!trimmed_id_tran_typ_ || strlen(trimmed_id_tran_typ_) < 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;
}