分配时出现分段错误

segmentation fault when allocating

我遇到了分段错误,希望能帮助我理解我做错了什么。

经过一段时间的代码 运行 我收到了一个核心转储: 程序因信号 SIGSEGV、分段错误而终止。

struct config {
    int a;
    int b;
    int c;
    int d;
};

static config* configuration_table = NULL;

void Album::caller() {
   
    replay(2, configuration_table, 0, false);
}

int Album::replay(int count, config*& config_tbl, unsigned int& config_sz, bool send) {
    int num_elems =0;

    ...
    ...
    ...

    err = get_num_elems(&num_elems);
    if (err) {
        return -1;
    }

    if (!num_elems) {
        return -1;
    }

    if (config_tbl) {
        delete[] config_tbl;
        config_tbl = NULL;
        config_sz = 0;
    }
    
    config_tbl = new config[num_elems];
    if (!config_tbl) {
        return -1;
    }
}

gdb:

4 0xf9abd319 in Album::replay (this=0xa693955, count=2, config_tbl=@0xf9d4299e: 0x0, config_sz=@0xa3039fe: 0, send=false)

从回溯看来,问题出在来自“config_tbl = new config[num_elems];[=24= 的运算符“new”的 malloc ]”。 num_elems 我调试时大小为 15。

我不明白我做错了什么。有没有可能是系统内存不足?

您的代码假定 config_tbl 已正确初始化。由于您坚持认为您发布的代码是所有相关的,所以我认为它没有正确初始化。

考虑这个简化的例子:

void foo( int* ptr) {
    if (ptr) delete ptr;
}

如果 ptrnullptr 或有效指针(即它指向通过 new 创建的 int),这很好。正确用法是

foo(nullptr);

int* x = new int;
foo(x);

然而,foo太容易搞砸了:

int* x;
foo(x);      // UNDEFINED BEHAVIOR
int y;
foo(&y);     // BOOM

首先不要对动态数组使用指针。请改用 std::vector

PS:请注意,虽然 foo 是非常糟糕的代码,但它并没有错。可能导致崩溃的是调用代码。