重复reallocs后的段故障
Segfault after repeated reallocs
编辑:非常感谢你的回答。这是对的,我将尝试使用向量代替。
我有一个动态分配内存的程序。
这个类有一个属性,它是一个结构数组(**)和一个指针数组(*),指向结构数组的每个元素,所以我做了2个malloc。这个结构体叫做context。
realloc工作正常,不返回NULL,但只要我有超过2个元素,程序会给我一个段错误,当试图保存数组元素中的值。如何防止这种分段故障?
int my_class::method(uint32_t struct_element)
{
int i= this->numofcontexts;
if(this->local_context_array == NULL)
// That means it is empty and we have to make our first malloc
{
this->local_context_array = (context_t**) malloc(sizeof(context_t*));
*(this->local_context_array) = (context_t*) malloc(sizeof(context_t));
i++;
std::cout << "n1 Malloc was made of size " << sizeof(context_t)<<"n";
}
else
// Array is not empty and we have to use realloc
{
this->local_context_array = (context_t**) realloc(this->local_context_array, (i+1)*sizeof(context_t*));
*(this->local_context_array) = (context_t*) realloc(*(this->local_context_array), (i+1)*(sizeof(context_t)));
std::cout << "n1 Realloc was made of size " << (i+1)*(sizeof(context_t)) <<"n";
i++;
std::cout << "nWe now have " << i <<" elementsn";
// As soon as the array is bigger than 2 elements, this gives segmentation fault:
//(this->local_context_array[i-1])->struct_element = struct_element;
}
从发布的代码和您描述的症状来看,您似乎没有在最后执行此操作:
this->numofcontexts = i;
如果这是真的,那么每次你调用这个方法,它会发现nummofcontexts == 0和local_context_array不是NULL,所以它会移动到你的else子句,当它将数组重新分配到i+1(总是1)。
第一次调用将成功,第二次调用也将成功,数组大小为1个元素,如果您尝试在此时分配元素超过[0],您可能会得到一个段错误。在[1]处可能没有出现段错误的原因通常与占用空间并被丢弃的其他变量有关,但这些变量并不总是立即产生段错误。
相关文章:
- Python & C-C++ 扩展模块案例段故障
- 中断;导致段故障
- 带指针的调用函数会导致段故障
- 由于变量范围导致的段故障
- 为什么通过shared_from_this()会导致段故障
- 简单的C++字符数组加密功能 - 段故障
- std::vector的函数push_back中的堰段故障
- 在openCV中将cvPoint[][]转换为cvPoint**时出现段故障
- 模板变量分配段故障11
- CIN 一个非常大的 int 数组,段故障 11
- C++段故障错误
- 段故障 -> 在标准::basic_ostream<字符中,标准::char_traits<char>
- C++中的二叉树段故障
- 调试执行工作正常,但正常的一段故障
- c++:几乎相同的输入,但第二次调用显示段故障
- 段故障。地址0x0不是堆叠的、恶意的或(最近)释放的
- 使用矢量引起的段故障
- 使用arm-linux- gnuabi -g++ -o时出现段故障,不使用-o也不会出现问题
- 为什么会出现以下段故障
- 在类文件和缓冲区中查找段故障