这对我来说似乎是一个相当奇怪的错误。我的 C++ 程序出现了段错误,使用 GDB 时我发现了一些奇怪的东西。我有以下构造函数和复制构造函数:
Bank::Bank(char mode, int floor_dimensions_, int num_floors_) : floor_dimensions(floor_dimensions_), num_floors(num_floors_) {
for (int i = 0; i < num_floors; i++) {
floors[i] = new Floor(floor_dimensions);
}
if (mode == 'M') {
read_map(floors);
} else if (mode == 'C') {
read_coords(floors);
}
}
Bank::Bank(const Bank& b) {
floor_dimensions = b.floor_dimensions;
num_floors = b.num_floors;
cout << floor_dimensions << endl;
cout << num_floors << endl;
for (int i = 0; i < num_floors; i++) {
floors[i] = new Floor(*b.floors[i]);
floors[i]->print_map();
}
这个类的定义类似于
class Bank {
/** The number of floors the bank has */
int num_floors;
/** The dimension of each of the floors */
int floor_dimensions;
/** The floors in the bank */
Floor* floors[];
private:
Bank(char mode, int floor_dimensions_, int num_floors_);
Bank(const Bank& bank);
~Bank();
void read_map(Floor** floor);
void read_coords(Floor** floor);
}
现在我使用 GDB 在构造函数的第一行设置断点。在执行了接下来的两行之后,b.floors[1] 的值发生了变化,这导致我调用b.floors[i]->foo()
.
Breakpoint 1, Bank::Bank (this=0x7fffffffe050, b=...) at bank.cpp:29
29 floor_dimensions = b.floor_dimensions;
(gdb) p b.floors[0]
$4 = (Floor *) 0x610070
(gdb) p b.floors[1]
$5 = (Floor *) 0x6103f0
(gdb) p b.floors[2]
$6 = (Floor *) 0x610770
(gdb) n
30 num_floors = b.num_floors;
(gdb) p b.floors[0]
$7 = (Floor *) 0x610070
(gdb) p b.floors[1]
$8 = (Floor *) 0x8006103f0
(gdb) p b.floors[2]
$9 = (Floor *) 0x610770
(gdb) n
32 cout << floor_dimensions << endl;
(gdb) p b.floors[0]
$10 = (Floor *) 0x610070
(gdb) p b.floors[1]
$11 = (Floor *) 0x800000003
(gdb) p b.floors[2]
$12 = (Floor *) 0x610770
有谁知道发生了什么?