分配时出现分段错误

segmentation fault when allocating

本文关键字:分段 错误 分配      更新时间:2023-10-16

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

在我的代码运行一段时间后,我收到了一个核心转储: 程序因信号 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;
}
}

分行:

专辑中的 4 0xf9abd319::重播(这=0xa693955,计数=2,config_tbl=@0xf9d4299e:0x0,config_sz=@0xa3039fe:0,发送=假(

从回溯看来,问题出在 malloc 上,它来自运算符"new",来自">config_tbl = new config[num_elems];". 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代码非常糟糕,但它并没有错。它是可能导致崩溃的调用代码。