我以前从未见过这个。比较两个整数时出现段错误。
编辑:忘记包括最令人沮丧的部分:它在 DDD 中运行良好,所以我无法调试它。
这是我的 gdb session 回溯段错误:
> Reading symbols from /home/michael/ecs60/hw3/3/huffman...done.
[New LWP 4109]
warning: Can't read pathname for load map: Input/output error.
Core was generated by `./huffman -d'.
Program terminated with signal 11, Segmentation fault.
#0 0x000000000040123a in huffnode::operator< (this=0x1e39010, hn=...)
at huffnode.h:54
54 if(weight < hn.weight) {
(gdb) bt
#0 0x000000000040123a in huffnode::operator< (this=0x1e39010, hn=...)
at huffnode.h:54
#1 0x00000000004021f4 in minheap<huffnode>::add (this=0x7fff15de7490,
n=...) at minheap.h:65
#2 0x0000000000401cb4 in decompress () at main.cpp:198
#3 0x00000000004012bb in main (argc=2, argv=0x7fff15de75f8)
at main.cpp:41 <
这是有问题的代码:
bool huffnode::operator<(const huffnode& hn) {
if(weight < hn.weight) {
return true;
} else if(weight == hn.weight) {
return small < hn.small;
} else {
return false;
}
};
这是调用违规代码的函数:
template<class T>
void minheap<T>::add(T n) {
if(size + 1 > capacity)
incCapacity();
heap[size] = n;
int index = size;
if(index == 0) return;
while(heap[index] < heap[(index + 1)/2 -1] && index != 0) {
swap(index, ((index+1)/2 - 1));
index = ((index + 1)/2 - 1);
}
size++;
};
这是调用 minheap::add 的解压部分:
unsigned int freq[NUM_CHARS];
for(int i = 0; i < NUM_CHARS; i++) {
in = getNum();
freq[i] = in;
}
for(int i = 0; i < NUM_CHARS; i++) {
if(freq[i] > 0) {
tree.add(huffnode((int)freq[i], (char) i));
}
}
谢谢大家!段错误已修复,但现在我的程序有一半显然依赖于损坏的代码,所以回到 DDD。
最佳答案
根据您的堆栈跟踪,hn
是...
,这表明它可能指向错误的内存(并且鉴于您遇到段错误,几乎可以肯定是这样)。你确定 huffnode
传递给运算符重载是否有效?初始化了吗?
进一步检查堆栈跟踪,n
在你的minheap<huffnode>::add
功能也无效,这意味着 add
正在传递无效的 huffnode
. add
看起来它是从 decompress
调用的, 自 decompress
不接受任何参数,它很可能在那里你传递了一个无效的 huffnode
至 add
.
鉴于add
正在直接传递 huffnode
的返回值构造函数,看起来它不会得到一个无效的对象,所以可能是 ...
在堆栈跟踪中具有误导性。
我要检查的下一个问题是你的比较 heap[index] < heap[(index + 1)/1 - 1]
.请注意,如果 index
是0
,则第二个运算符将为 heap[-1]
, 这是无效的。你能确保index
吗?永远不会0
还是更少?
作为旁注,我想指出整个条件:
heap[index] < heap[(index + 1)/2 - 1] && index != 0
即使在 index
时也会失败等于0
因为<
运算符将首先被评估,导致段错误。您应该选择 0
检查条件之外和之前,或作为第一个条件。
最后,如果这是只在调试器之外出现的错误类型,那么 print
语句成为你的 friend (粗略的,是的,但如果你知道要打印什么,它们就可以完成工作)。我建议将打印添加到 add
在你的 while
的每次迭代中循环,检查什么 index
是。您也可以在 add
的开头打印n
的地址是什么是,看看它是否看起来像未初始化的内存。鉴于您如何添加 huffnode
s 到你的数据结构,我很确定你的问题是越界访问你的 heap
数组。
关于c++ - 比较时出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13678640/