[英]Segmentation fault (core dumped) - Access violation reading location x
我正在編寫某種玩具程序以進入C ++。 但是我在代碼的非常特定的行遇到了段錯誤的很多麻煩。 我知道分段錯誤意味着我嘗試訪問未分配給程序的memort。 代碼如下所示(實際上太大了,無法僅復制粘貼):
class car {
protected:
int speed;
std::string brand;
public:
car (int s, std::string b):speed(s),brand(b) {
std::cout << "New car has been created" << endl;
}
virtual int is_stopped () {
if (speed==0) return 1;
else return 0;
}
virtual void speed_up () {
speed++;
}
car* clone () {
car* tmp(this);
return tmp;
}
};
class fast_car : public car {
public:
fast_car (int s, std::string b):car(s,b) { }
};
class slow_car : public car {
public:
slow_car (int s, std::string b):car(s,b) { }
};
class highway {
int number_of_cars;
car **first; //There are derived classes from car hence the double pointer
public:
highway (int c, int s, std::string b):number_of_cars(c) {
first = new car*[c];
for (int i=0;i<c/2;i++)
first[i] = new fast_car (s,b);
for (int i=c/2;i<c;i++)
first[i] = new slow_car (s,b);
}
void speed_up () {
int pos;
pos = rand()%number_of_cars; //give me a random number between 0 and number_of_cars;
if (pos!=0) pos--; //We don't want position -1
first[pos]->speed_up ();
clone_fast (first[pos], (number_of_cars - pos - 1)); //the second argument is the remaining array "spots" until the end of the array
}
void clone_fast (car* cur, int rem) {
car* tmp;
for (int i=-;i<=rem;i++)
if ((cur+1)->is_stopped ()) { //Exact line where I get the segmentation fault
tmp = cur->clone ();
cur++;
}
}
};
就是這樣。 我試圖為您提供一切我可以重現該問題的方法。 我將嘗試解決任何其他問題。 任何幫助將不勝感激。
car*
由new
創建,並不一定是連續的; 它們肯定不是指針運算的數組。 (car*) + 1
與(car**)[i + 1]
(更像是(car**) + 1
)。 您可能想要的東西更像(*(first + 1))->doThing()
,而不是(first[X] + 1)->doThing()
。
編輯:更清楚一點,如果您不能做car[X + 1]
,那么您就不能做*(car + 1)
。 由於clone_fast()
中的car
是對象指針而不是數組,因此無法執行car[X + 1]
,因此(cur + 1)->is_stopped()
是錯誤的。
我建議刪除所有指針廢話,並使用更多現代習語。 您可以在下面的代碼上展開。 但是,我不清楚您為什么有兩個派生類:它們既沒有特定的數據又沒有方法,那么為什么呢?
class car
{
private:
int speed;
std::string brand;
public:
car (int s, std::string b):speed(s),brand(b)
{
std::cout << "New car has been created" << endl;
}
bool is_stopped ()
{
return speed==0;
}
void speed_up ()
{
speed++;
}
};
class fast_car : public car
{
public:
fast_car (int s, std::string b):car(s,b) {}
};
class slow_car : public car
{
public:
slow_car (int s, std::string b):car(s,b) {}
};
class highway
{
private:
std::vector<std::shared_ptr<car>> v_cars;
public:
highway (int c, int s, std::string b):number_of_cars(c)
{
for (int i=0;i<c/2;i++)
v_cars.push_back( std::make_shared<fast_car>(s,b) );
for (int i=c/2;i<c;i++)
v_cars.push_back( std::make_shared<slow_car>(s,b) );
}
};
int main()
{
highway h( 50, 20 );
return 0;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.