C和字符串处理

完全代码http://pastebin.com/6bdVTyPt我的树代码完全正常工作,直到我发现我需要validation其不是文本的ID所以它必须是字符串插入函数字符串比较90和129返回8试图使用(atoi)和比较整数不起作用任何帮助赞赏
谢谢你inheritance使用atoi而不是strcomp的插入functionhttp://pastebin.com/yeuktyAF仍然没有工作插入function

struct node * insert2(struct node *root, char x[],char id[]) { if(!root) { root=(struct node*)malloc(sizeof(struct node)); free( root->data ); free( root->id );// free previously allocated memory, if any root->data = strdup( x ); // malloc and copy root->id=strdup(id); root->left = NULL; root->right = NULL; // printf("1\n"); return(root); } printf("string comp %d of %s of %s\n",strcmp(root->id,id),root->id,id); if((strcmp(root->id,id))>0){ root->left = insert(root->left,x,id); printf("go left\n"); } else { if(strcmp(root->id,id)right = insert(root->right,x,id);} } return(root); } 

这条线

 root=(struct node*)malloc(sizeof(struct node)); 

root分配内存但不初始化它。 这意味着以下几行

 free( root->data ); free( root->id ); 

试图释放未初始化(如此不可预测)的指针。 这几乎肯定会崩溃。

由于您只是刚刚分配了root因此dataid任何先前值都不可能被释放。 这意味着您可以简化这三行

 root=malloc(sizeof(*root)); 

您无法使用strcmp()比较数字字符串。 您应该将您的ID:s存储为整数,如果它们是这样的,那么您可以直接比较它们。

这也有复杂性较低的好处,因为整数是固定大小的(假设unsigned long long足够长)你不需要使用strdup()

另外, 不要在C中malloc()的返回值 。