我必须为2d点构建一个2d树。在插入节点时,我正在检查树是否已经包含相同的点。这在DevC++中提供了SEGFAULT,但相同的代码在任何其他编译器中都可以运行。
需要重新运行的代码。
#include <stdlib.h>
#include <stdio.h>
#include <stdbool.h>
//INPUT 0.6 0.5 0.4 0.3 0.8 0.6 0.1 0.4 0.6 0.9
#define VERTICAL 1
#define HORIZONTAL 0
int size = 0;
typedef struct point2d {
double x;
double y;
}point;
typedef struct KdTree {
point pt;
int division;
struct KdTree *left,*right;
}Node;
bool isLessThan(point node,point root,int division) {
return division == VERTICAL ? node.x < root.x : node.y < root.y;
}
int getDivisionByNode(Node *node) {
return node->division == VERTICAL ? HORIZONTAL : VERTICAL;
}
bool equals(point p, point q) {
return (p.x==q.x && p.y == q.y );
}
SEGFAULT在以下函数中访问current->pt
时发生。如果存在NULL,不知道为什么在DevC++中跳过if(current==NULL)
。
bool contains(Node *root,point p) {
Node *current = root;
while(true){
if(current == NULL){
return false;
}
if(equals(current->pt,p)) //SEGFAULT
return true;
if(isLessThan(p,current->pt,current->division)) //SEGFAULT
current = current -> left;
else
current = current->right;
}
}
其他插入功能如下:
Node* insertNode(Node *node,Node *parent){
if(parent==NULL){
node->division = VERTICAL;
return node;
}
if(isLessThan(node->pt,parent->pt,parent->division)) {
if(parent->left == NULL) {
node->division = getDivisionByNode(parent);
parent->left = node;
}
else
parent->left = insertNode(node,parent->left);
}
else {
if(parent->right == NULL) {
node->division = getDivisionByNode(parent);
parent->right = node;
}
else
parent->right = insertNode(node,parent->right);
}
return parent;
}
Node* insert(Node *root, point p){
if(!contains(root,p)){
Node *node = malloc(sizeof(*node)); //check here
node->pt.x=p.x;
node->pt.y=p.y;
root = insertNode(node,root);
size++;
}
return root;
}
驱动程序代码
int main() {
Node *root = NULL;
int i;
double x,y;
point p;
for ( i = 0; i < 5; ++i) {
scanf("%lf %lf",&x,&y);
p.x = x;
p.y = y;
root = insert(root,p);
printf("[%f,%f]",root->pt.x,root->pt.y);
}
}
需要做些什么才能删除SEGFAULT并在DevC++中正确运行它?
您通过使用Node
的成员left
和right
的不确定值来调用未定义的行为,而这些值是通过malloc()
分配的并且未初始化。
像这样初始化它们:
Node* insert(Node *root, point p){
if(!contains(root,p)){
Node *node = malloc(sizeof(*node)); //check here
node->pt.x=p.x;
node->pt.y=p.y;
node->left=NULL; /* add this */
node->right=NULL; /* add this */
root = insertNode(node,root);
size++;
}
return root;
}