我在使用struct * queue时遇到了SIGSEGV错误(Segmentation fault 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("%lld\n",result_fix);
printf("%lld\n",result_huff);
return 0;
}
答案 0 :(得分:1)
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);