繁体   English   中英

调用析构函数时出现分段错误

[英]Segmentation fault when calling destructor

嘿伙计们,我是 C++ 的新手,这是我的学期项目。 当我在堆栈上创建 IPADDRESS object 时,main.cpp 文件将运行,直到为 IPADDRESS object 调用解构器成员。 第一部分运行良好,第二部分返回相同的 output,只是分段错误。

// Main file
#include <bits/stdc++.h>
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <string>
#include "IPInfo.h"

using namespace std;

// Function declaration of display()
void displayInfo(IPADDRESS);

int main(){

    const char* address = "cbc.ca";
    const char* command = "nslookup ";

        char buf[256];
        strcpy(buf, command);
        strcat(buf, address);

        string* Info = new(nothrow) string[256]; // Allocate 256 bytes to this string
        *Info = system(buf); // Allocate the response from the command line to Info (which is on the heap)
    cout << Info << endl << *Info << endl << "===============================" << endl << endl;
    delete[] Info;

    IPADDRESS test("cbc.ca");

    displayInfo(test);

// Displays but never exits the program correctly

    return 0;
}
void displayInfo(IPADDRESS Website){

    string* displayBus;
    displayBus = Website.getInfo();
    cout << displayBus;
}
// Header file
#ifndef IPInfo_H
#define IPInfo_H

#include <bits/stdc++.h>
#include <string>
#include <iostream>

using namespace std;
class IPADDRESS{
private:
    const char* command = "nslookup ";
    string url;
    string info;
    string address;
    int searchFor(string locator); // Find a substring in the getInfo string

public:
    string* getInfo(); // Using the system("nslookup") call, get the info (Will be allocated to heap)
    IPADDRESS(string website);
    ~IPADDRESS();
    string getIPAddress(); // Using searchFor() get rid of unneeded characters and dump the IPAddress to a string
    string getName(); // Also output the name

};

IPADDRESS::IPADDRESS(string website){
    url = website;
}

IPADDRESS::~IPADDRESS(){
}
#endif

这是不正确的

IPADDRESS::~IPADDRESS(){

    delete &address;
    delete &url;
    delete &info;
    delete command;
}

您不能也不应该delete您没有new的任何变量。

默认的编译器生成的析构函数在这里已经足够且正确(您可以完全删除它,在这种情况下它将隐式生成)。

~IPADDRESS() = default;  // don't even need this, compiler will generate in this case

delete用于释放通过new分配的内容,否则不得使用它。

目前您发布的代码不包含new ,因此析构函数应该是:

IPADDRESS::~IPADDRESS(){
}

另请注意,如果您使用动态 memory 分配,则应遵循三法则 最好避免在 C++ 中进行裸动态 memory 分配。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM