嗨,我在使用结构 * 队列时遇到了 SIGSEGV 错误(分段错误 11)。这段代码是关于霍夫曼代码的,我正在使用priority_queue来实现算法。我想问题,也许我的代码需要初始化队列。无论你如何尝试解决它。我不使用这样的指针式队列吗?请帮帮我...
typedef struct NODE{
long long int freq;
string s;
struct NODE* left;
struct NODE* right;
}Node;
int main(){
priority_queue<Node*,vector<Node*>, compare > q;
Node* root;
scanf("%d",&n);
int power = find_power(n);
string a;
long long int b,total;
for (int i=1; i<=n; i++) {
Node* tmp = (Node*)malloc(sizeof(Node*));
cin >> a >> b;
tmp->freq = b;
tmp->s = a;
tmp->left = NULL;
tmp->right = NULL;
q.push(tmp);
}
scanf("%lld",&total);
result_fix = power * total;
for (int i=1; i<n; i++) {
Node *z = (Node *)malloc(sizeof(Node*));
Node* x = (Node *)malloc(sizeof(Node*));
Node* y = (Node *)malloc(sizeof(Node*));
x = q.top();
q.pop();
y = q.top();
q.pop();
z->left = x;
z->right = y;
z->s = "";
z->freq = x->freq + y->freq;
q.push(z);
free(x);
free(y);
}
root = (Node *)malloc(sizeof(Node*));
root = q.top();
q.pop();
if (!q.empty()) {
printf("Queue is not empty!n");
}
find_bit(root,0);
printf("%lldn",result_fix);
printf("%lldn",result_huff);
return 0;
}
Node *z = (Node *)malloc(sizeof(Node*));
// ...
x = q.top();
由于双重错误,这是未定义的行为:
- 当您需要内存用于
Node
时,您分配了存储Node*
所需的内存; - 使用
malloc
分配内存时,内存未初始化:不构造对象。当你影响它时(x = q.top();
),你在一个非构造对象上调用Node::operator=
。
作为解决方案,我建议学习C++而不是用类编写 C。但作为更具体的解决方案:
Node z = q.top;
或
Node *const z = new Node(q.top);