用strcmp()比较两个字符串给出了EXC_BAD_ACCESS

时间:2018-05-09 18:14:08

标签: c string strcmp red-black-tree string.h

我有这个功能在红黑树中插入一个节点。此红黑树的顺序键是字符串id_prod,通过函数strcmp进行比较。当我尝试在此结构中插入节点时,Xcode会向我发出此警报EXC_BAD_ACCESS

这是功能:

void insert_id(node *sent, node *new_node)
{
    if (sent->parent == NULL)
    {
        new_node->left = new_node->right = sent;
        sent->parent = new_node;
        new_node->color_node = black;
    }
    else
    {
        node *temp = malloc(sizeof(struct node));

        temp = sent->left;

        while (temp != sent)
        {
            if(strcmp(temp->id_prod, new_node->id_prod) < 0)
            {
                temp = temp->left;
            }
            else
            {
                temp = temp->right;
            }
        }
        if (strcmp(new_node->id_prod, temp->id_prod) < 0)
        {
            temp->left = new_node;
            new_node->parent = temp;
        }
        else
        {
            temp->right = new_node;
            new_node->parent = temp;
        }
        new_node->left = new_node->right = sent;
        new_node->color_node = black;
        setup_tree(sent, new_node);
    }
    return;
}

字符串在文件中。这是从文件读取和分配数据到struct节点的函数:

结构:

typedef struct node
{
color   color_node;
char    id_prod[5],         
        name[20],           
        id_piece[5];        
struct  node    *left,
                *right,
                *parent;
} node;

功能:

node* get_node_file(FILE *in)
{
node *new_node = (node*) malloc(sizeof(node));

fscanf(in, FORMAT_IN,   new_node->id_prod,
                        new_node->name,
                        new_node->id_piece);


new_node->left = NULL;
new_node->right = NULL;
new_node->parent = NULL;
new_node->color_node = black;
return new_node;
}

这是主要的:

#define STORE "Magazzino.txt"

int main()
{

FILE    *input;
node *sent = malloc(sizeof(struct node));
sent->color_node = black;
sent->left = sent->right = sent->parent = NULL;


input = fopen(STORE, "r");

insert_id(sent, get_node_file(input));
insert_id(sent, get_node_file(input));
insert_id(sent, get_node_file(input));



return 0;
}

0 个答案:

没有答案