-4

这对我来说似乎是一个相当奇怪的错误。我的 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

有谁知道发生了什么?

4

1 回答 1

2

您的代码的问题很可能是您试图访问未初始化的指针 ( b.floors)。假设b是这个复制构造函数的结果,那么b.floors将指向随机内存。b.floors[i]然后将指向随机内存一些字节b.floors指向的内容,最终您使用->取消引用此随机地址,这会导致分段错误。

您的问题的解决方案是正确分配和复制楼层数组:

floors = new Floor* [num_floors];
for (int i=0; i<num_floors; ++i)
  floors[i] = b.floors[i];

您可能还想复制指向的 object Floor,具体取决于您的实现细节。

于 2012-09-26T03:07:48.527 回答