分配时出现分段错误
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;
}
}
分行:
专辑中的 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;
}
如果ptr
是nullptr
或有效的指针(即它指向通过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
代码非常糟糕,但它并没有错。它是可能导致崩溃的调用代码。
相关文章:
- 在某些循环内使用vector.push_back时出现分段错误
- 为什么在运行时没有向我们提供有关分段错误的更多信息?
- 如何解决gcc编译器优化导致的centos双编译器设置中的分段错误
- 当我的阵列太大时出现分段错误
- 分段错误当我试图运行程序时出错
- 在c++中初始化矩阵时出现分段错误(核心转储)
- 尝试使用集合函数时出现分段错误
- 我无法缩小此分段错误的原因
- g++的分段错误(在NaN上使用to_string两次时)
- 我是如何在这段代码中出现分段错误的
- 创建结构的数组时遇到分段错误
- 在c++中键入向量中的所有值后,得到分段错误(核心转储)
- 在 c++ 中实现 Trie 时出现分段错误
- 为什么 fstream 在打开带有格式的文件时会导致分段错误?
- 为什么我遇到分段错误?
- 动态类的分段错误(家庭作业问题)
- 分段错误 - 读取初始化指针的数组
- 如何摆脱C ++中的分段错误错误?
- 使用 CTYPE 时出现分段错误
- 为什么代码给出分段错误?