SIGSEGV 尝试更改结构 C/C++ 中的字符串时
SIGSEGV when trying to change string in structure C/C++
我有一个这样的结构
typedef struct {
string aPath;
string dPath;
string tmpPath;
int cSet;
int socket;
} threadParams;
还有一些像这样的变量
string dirPath = "./Maildir/";
string authPath;
string tmpPath = "~/tmpPath/";
我试图初始化结构并添加一些这样的数据
threadParams *tP = (threadParams*)malloc(sizeof(threadParams));
tP->aPath = authPath;
tP->cSet = cParam;
tP->dPath = dirPath;
tP->socket = commSocket;
tP->tmpPath = tmpPath;
当我使用此代码运行程序时,在尝试执行此代码时会出现 SIGSEGV 信号:tP->aPath = authPath; 当我删除结构的这些字符串成员并只保留 int 变量时,一切正常。
谁能告诉我为什么会发生这种情况以及如何解决它?谢谢
当你分配结构时,你只是分配了threadparams结构的大小。 基础字符串未正确构造。 在内部,它们是指向未分配内存的指针。
如前所述,在创建动态对象时,使用"new",这将分配并正确构造对象及其包含的所有对象元素。