C++类内结构体内存溢出问题
void ProbeDecorator::GenSoap()
{
this->soap = "";
this->add = "";
this->soap.append("<?xml version=\"");
this->add = this->message->http_content->xml_info->version;
soap.append(add);
**cout << this->message->http_content->xml_info->encoding << endl;**
this->soap+="\"";
this->soap+=" encoding=\"";
;
}
当我将cout << this->message->http_content->xml_info->encoding << endl;这一句放在上面这个位置的时候,不会报错,
但是如果我放在了this->soap+="encoding=\“";这句后面的话,就会出现Segmentation Fault报错
所有结构体中用不上的指针我全部赋成了0
为什么会报错,如何解决,
代码修改如下:
#include <iostream>
#include <string>
using namespace std;
struct Xml_Info
{
char *encoding;
char *version;
};
struct Http_Content
{
//char *content_length;
Xml_Info *xml_info;
//Xml_element *envelope;
};
struct Message
{
//Http_Header *http_header;
Http_Content *http_content;
};
class ProbeDecorator
{
public:
Message message;
void Init();
void GenSoap();
string soap, add;
};
void ProbeDecorator::Init()
{
Http_Content* http_content = new Http_Content;
Xml_Info* xml_info = new Xml_Info;
http_content->xml_info = xml_info;
this->message.http_content = http_content;
xml_info->version = new char[6];
memset(xml_info->version,0,6);
memcpy(xml_info->version,"1.0",3);
xml_info->encoding = new char[6];
memset(xml_info->encoding,0,6);
memcpy(xml_info->encoding,"utf-8",5);
cout << this->message.http_content->xml_info->version << endl;
cout << this->message.http_content->xml_info->encoding << endl;
}
void ProbeDecorator::GenSoap()
{
cout << this->message.http_content->xml_info->version << endl;
cout << this->message.http_content->xml_info->encoding << endl;
;
}//你看看我这样申请这样对么
int main()
{
ProbeDecorator c;
c.Init();
c.GenSoap();
return 0;
}
更正一下:
如果我将cout << this->message->http_content->xml_info->encoding << endl;放在soap.append(add);后面的话也会报Segmentation Fault而只有放在this->add = this->message->http_content->xml_info->version;后面不会报错
+=是c#的语法,c++不能这样字符串拼接
具体为何错误,请学会调试,看看是否有空指针,或者访问越界
您好,我是有问必答小助手,您的问题已经有小伙伴帮您解答,感谢您对有问必答的支持与关注!