SEGFAULT 出现在 DevC++ 中,但不会出现在其他编译器中

SEGFAULT occurs in DevC++ but not in other compilers

我必须为 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 );
}

在以下函数中访问 current->pt 时发生 SEGFAULT。如果存在 NULL,不知道为什么 if(current==NULL) 在 DevC++ 中被跳过。

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;
}

driver代码

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);
    }
}

要在 DevC++ 中正确删除 SEGFAULT 和 运行 需要做什么?

您正在通过使用 Node 的成员 leftright 的不确定值来调用 未定义的行为 ,而它们是通过 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;
}