Как найти дамп ядра? Сузили до конструкторов и функций

Я получаю ошибку дампа ядра (утечка памяти), и я не уверен, откуда она. Я попытался запустить части программы одновременно и минимизировал проблему. Любая помощь будет оценена. Спасибо

Базовый заголовочный файл.

#ifndef VEHICLE_H
#define VEHICLE_H

#include <iostream>
#include <string>
using namespace std;

class Vehicle{
protected:
char *name;
static ostream *out ;
public:
Vehicle();
Vehicle(string &n);
Vehicle (const Vehicle & b);
~Vehicle();
Vehicle& operator =(const Vehicle &b);
virtual void print(void) = 0;
virtual void read(void) = 0;

};

Базовые Конструкторы

#include "vehicle.h"#include <iostream>
#include <cstring>

ostream * Vehicle :: out = &cout;

Vehicle :: Vehicle(){

name = new char;
strcpy(name, "");
}

Vehicle :: Vehicle(string &n){

int len = n.length()+ 1;
delete [] name;
name = new char[len];
strcpy(name,n.c_str());

}

Vehicle :: Vehicle(const Vehicle & v){

int len = strlen(v.name)+ 1;
delete [] name;
name = new char[len];
strcpy(name,v.name);

}
Vehicle & Vehicle::operator = (const Vehicle &b){

if(this == &b){

return *this;

}

int len = strlen(b.name)+ 1;
delete [] name;
name = new char[len];
strcpy(name,b.name);

return *this;
}

Vehicle:: ~Vehicle(){

delete [] name;

}

Производный заголовочный файл

#ifndef MOTORVEHICLE_H
#define MOTORVEHICLE_H

#include <cstring>
#include "vehicle.h"
class MotorVehicle: public Vehicle{
protected:
string make;
string model;
double mpg;
public:
MotorVehicle();
MotorVehicle (const string &n,const string &m = "",const string &md = "", const double &mp = 0.0);

//accessor functions
string getName()const;
string getMake()const;
string getModel()const;
double getMpg()const;
ostream & getOut();

//mutator functions
string setName();
void setMake();
void setModel();
void setMpg();
void setOut(ostream & o);

//virtual functions
void print();
void read();

};

#endif // MOTORVEHICLE_H

Реализация автомобилей. Вот где происходит ошибка.

#include "motorVehicle.h"#include <string>
#include <iostream>

MotorVehicle:: MotorVehicle(): Vehicle(), make(""), model(""), mpg(0.0){
make = "";
model = "";
mpg = 0.0;

}

MotorVehicle :: MotorVehicle(const string &n, const string &m, const string &md, const double &mp){

int len = n.length()+ 1;
delete [] name;
name = new char[len];
strcpy(name,n.c_str());

make = m;
model = md;
mpg = mp;

}

//accessor functions

string MotorVehicle :: getName()const{

string temp(name);
return temp;

}

string MotorVehicle :: getMake()const {

return make;

}

string MotorVehicle :: getModel()const {

return model;

}

double MotorVehicle :: getMpg()const {

return mpg;

}

ostream & MotorVehicle  :: getOut(){

return *out;
}

//mutator functions
string MotorVehicle :: setName(){
cerr << "dododd" <<endl;

string nm1;
cin >> nm1;

int len = nm1.length()+ 1;
delete [] name;
name = new char[len];
strcpy(name,nm1.c_str());}

void MotorVehicle :: setMake(){

cin >> make;
}

void MotorVehicle :: setModel(){

cin >> model;

}

void MotorVehicle :: setMpg(){

cin >> mpg;
}

void MotorVehicle :: setOut(ostream & o){

out = &o;
}

//virtual function
void MotorVehicle :: print(){

*out << name << make << model << mpg <<" ";
}

void MotorVehicle :: read(){*out << "Please enter name for this Vehicle:  " << endl;
setName();

*out << "Please enter make for this Vehicle:  " << endl;
setMake();

*out << "Please enter model for this Vehicle:  " << endl;
setModel();

*out << "Please enter miles per gallon for this Vehicle:  " << endl;
setMpg();}

Грузовик заголовок

#ifndef TRUCK_H
#define TRUCK_H

#include "motorVehicle.h"class Truck: public MotorVehicle{
protected:
double cargoCapacity;
public:
Truck();
Truck (string &n,string &m,string &md, double &mp , double &cp);
//accessor functions
double getcargoCapacity()const;

//mutator functions
void setcargoCapacity();

//virtual functions
void print();
void read();

};

#endif

Реализация грузовика

#include "truck.h"
Truck :: Truck() : MotorVehicle(){

cargoCapacity = 0.0;
}Truck :: Truck(string &n, string &m, string &md, double &mp, double &cp ): MotorVehicle (n,m,md,mp){

cargoCapacity = 0.0;

}double Truck :: getcargoCapacity()const{

return cargoCapacity;

}

void Truck :: setcargoCapacity(){

cin >> cargoCapacity;

}

void Truck :: print(){

*out << name << make << model << mpg << cargoCapacity << " ";

}

void Truck :: read(){

*out << "Please enter cargo capacity for this Vehicle:  " << endl;
setcargoCapacity();

*out << "Please enter name for this Vehicle:  " << endl;
setName();

*out << "Please enter make for this Vehicle:  " << endl;
setMake();

*out << "Please enter model for this Vehicle:  " << endl;
setModel();

*out << "Please enter MPG for this Vehicle:  " << endl;
setMpg();

}

Автомобильный заголовок

#ifndef CAR_H
#define CAR_H

#include "motorVehicle.h"
class Car: public MotorVehicle{

private:
string trim;
public:
Car();
Car (string &n,string &m,string &md,double &mp, string &t);

//accessor functions
string getTrim()const;

//mutator functions
void setTrim();

//virtual functions
void print();
void read();

};#endif // CAR_H

Реализация автомобиля

#include "car.h"
Car :: Car (){

MotorVehicle();

}

Car :: Car(string &n, string &m, string &md, double &mp, string &t) : MotorVehicle (n,m,md,mp){

trim = "";
}

string Car :: getTrim()const{

return trim;

}

void Car :: setTrim(){

cin >> trim;
}

void Car :: print(){

*out << name << make << model << mpg << trim << " ";

}

void Car :: read (){

*out << "Please enter trim for this Vehicle:  " << endl;
setTrim();

*out << "Please enter name for this Vehicle:  " << endl;
setName();

*out << "Please enter make for this Vehicle:  " << endl;
setMake();
*out << "Please enter model for this Vehicle:  " << endl;
setModel();

*out << "Please enter MPG for this Vehicle:  " << endl;
setMpg();}

Главный

#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <typeinfo>
#include "motorVehicle.h"
// car.h & truck.h included twice to test #ifndef #define ... #endif structure
#include "car.h"#include "car.h"#include "truck.h"#include "truck.h"
typedef vector<MotorVehicle *> vectorOfMotorVehicle;

using namespace std;

// prompt the user for the Vehicle type to create, and get the reply
string prompt(void);

int main() {
vectorOfMotorVehicle v;         // store dynamically created MotorVehicles
// or objects derived from MotorVehicles
int           numVehicles = 0;  // denotes how many MotorVehicles we have
string        reply;            // indicates type of MotorVehicle to build
bool          error = false;    // set when a user response is in error
string        outputLocation;   // where the output of print() will go
ofstream     *out = NULL;
MotorVehicle *m;

// uncomment following line to test that Vehicle is an abstract base class
// Vehicle theVehicle;

// push a Vehicle into the vector so  first "real" Vehicle is at position 1
m = new MotorVehicle("None");
v.push_back(m);

// chose where the output will go
cout << "Where would you like the output?  ";
cin  >> outputLocation;

if (outputLocation == "stdout") {
; // no action to take, because stdout (i.e., cout) is the default
} else if (outputLocation == "stderr") {
v[0]->setOut(cerr);
} else {
out = new ofstream;
out->open(outputLocation.c_str());
if (out->fail()) {
cerr << "Error:  error writing to " << outputLocation << endl;
return 1;
}
v[0]->setOut(*out);
}

// get the type of Vehicle to create
reply = prompt();

// loop, reading vehicle descriptions, until a "quit" command is received
while (reply != "quit") {

// create the new MotorVehicle object and push it into the vector
switch (toupper(reply[0])) {
case 'T' : m = (MotorVehicle *) (new Truck);
v.push_back(m);
break;
case 'C' : m = (MotorVehicle *) (new Car);
v.push_back(m);
break;
case 'Q' : reply = "quit";
continue;
default  : cerr << "Incorrect response\n\n";
error = true;
}

// if no error, then we have a new Vehicle to initialize via read()
if (!error) {
numVehicles++;
v[numVehicles]->read();
}

// reset error flag, and request a new Vehicle type
error = false;
reply = prompt();
}

// report on what Vehicles were created to test read() and print()
for (int i = 0; i <= numVehicles; i++) {
//*out << "Vehicle " << i << endl;

// print the Vehicle characteristics (attributes)
v[i]->print();

//*out << endl;

// free the storage for this Vehicle
delete v[i];
}

// if we opened an output file, then close it
if (out != NULL) {
out->close();
delete out;
}

return 0;
}

// prompt the user for the Vehicle type to create, and get the reply
string prompt() {
string reply;    // the user reponse to the prompt

// prompt for and get user response
cout << "\nWhich type of vehicle would you like to initialize"<< "\n--car or truck (or \"quit\" to exit):  ";
cin  >> reply;

return reply;
}

Когда производные классы пытаются вызвать функцию setName, он продолжает генерировать дамп ядра. Откуда идет утечка?

Спасибо

-1

Решение

Не уверен на 100% в достоверности название в транспортном средстве, но вполне может быть NULL. Это будет проблемой в Имя набора как вы пытаетесь удалить [] NULL.

Так изменить

Vehicle :: Vehicle(){
name = '\0';
}

в

Vehicle :: Vehicle(){
name = new char[1];
name[0] = '\0';
}

и вы должны иметь реальное право собственности на эту память для удаления. Не забудьте также освободить выделенную память у desctrutor.

0

Другие решения

Других решений пока нет …

По вопросам рекламы [email protected]