ljc_1999 2022-02-22 11:04 采纳率: 100%
浏览 60
已结题

C++类内结构体内存溢出问题

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报错

img

img

所有结构体中用不上的指针我全部赋成了0
为什么会报错,如何解决,

  • 写回答

5条回答 默认 最新

  • 关注

    代码修改如下:

    img

    #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;
    }
    
    
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论 编辑记录
查看更多回答(4条)

报告相同问题?

问题事件

  • 系统已结题 3月2日
  • 已采纳回答 2月22日
  • 创建了问题 2月22日

悬赏问题

  • ¥15 FileNotFoundError 解决方案
  • ¥15 uniapp实现如下图的图表功能
  • ¥15 u-subsection如何修改相邻两个节点样式
  • ¥30 vs2010开发 WFP(windows filtering platform)
  • ¥15 服务端控制goose报文控制块的发布问题
  • ¥15 学习指导与未来导向啊
  • ¥15 求多普勒频移瞬时表达式
  • ¥15 如果要做一个老年人平板有哪些需求
  • ¥15 k8s生产配置推荐配置及部署方案
  • ¥15 matlab提取运动物体的坐标