Ошибка сегментации при вызове деструктора - PullRequest
0 голосов
/ 05 августа 2020

Привет, ребята, я новичок в C ++, и это для моего проекта. Когда я создаю объект IPADDRESS в СТЕКЕ, основной файл. cpp будет работать до тех пор, пока для объекта IPADDRESS не будет вызван член деконструктора. Первый раздел работает нормально, а второй раздел возвращает тот же результат, только с ошибкой сегментации.

// 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

Ответы [ 2 ]

4 голосов
/ 05 августа 2020

Это неверно

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
1 голос
/ 05 августа 2020

delete предназначен для освобождения того, что выделено через new, и вы не должны использовать его иначе.

В настоящее время ваш опубликованный код не содержит new, поэтому деструктор должен быть:

IPADDRESS::~IPADDRESS(){
}

Также обратите внимание, что вы должны следовать Правилу трех , если вы используете динамическое c распределение памяти. В C ++ лучше избегать голого динамического c выделения памяти.

...