C和字符串处理 [英] C and string handling

查看:139
本文介绍了C和字符串处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

FULL code http://pastebin.com/6bdVTyPt
我的树code的完美工作,直到我发现我需要验证它不是文本所以ID它必须是字符串
插入功能
字符串比较90和129的回报8
试图用(与atoi)和比较为整数不起作用
任何帮助AP preciated结果
谢谢
继承人使用的atoi代替STRC​​OMP插入功能
http://pastebin.com/yeuktyAF 仍无法正常工作
插入功能

 结构节点* insert2(结构节点*根,焦X [],CHAR ID [])
 {
如果(!根)
{
    根=(结构节点*)malloc的(的sizeof(结构节点));
    免费(根 - >数据);
    自由(根 - 和SEQ ID); //自由previously分配的存储器,如果有的话
    根 - >数据=的strdup(X); // malloc和复印件
    根 - 和SEQ ID =的strdup(ID);
    根 - >左= NULL;
    根 - >右= NULL;
    //输出(1 \\ n);
    返回(根);
}
的printf(字符串可比%S的\\ n的%s%D,STRCMP(根 - > ID,ID),根 - > ID,ID);
如果((的strcmp(根 - 和SEQ ID,ID))大于0){
    根 - >左=插入(根 - >左,X,ID);
    的printf(往左走\\ n);
}
其他
{
    如果(的strcmp(根 - 和SEQ ID,ID)℃,){
        的printf(向右走\\ n);
        根 - >右=插入(根 - >右,X,ID);}
}
返回(根);
}


解决方案

 根=(结构节点*)malloc的(的sizeof(结构节点));

分配内存,但不会初始化。这意味着下面的行

 免费(根 - >数据);
自由(根 - 和SEQ ID);

试图释放未初始化(未所以predictable)指针。这几乎肯定会崩溃。

既然你才刚刚分配有没有可能在数据的任何previous值 ID 免费。这意味着你可以简化这些三行

 根=的malloc(sizeof的(*根));

FULL CODE http://pastebin.com/6bdVTyPt My tree code was perfectly working until i found out i needed to validate the id that its not text so it had to be string insertion function string compare of 90 and 129 returns 8 tried to use (atoi) and compare as integers does not work any help appreciated
thank you heres the insert function using atoi instead of strcomp http://pastebin.com/yeuktyAF still not working insertion 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)<0){
        printf("go right\n");
        root->right = insert(root->right,x,id);}
}
return(root);
}

解决方案

The line

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

allocates memory for root but doesn't initialise it. This means that the following lines

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

attempt to free uninitialised (so unpredictable) pointers. This will almost certainly crash.

Since you've only just allocated root there can't possibly be any previous values in data or id to free. This means you could simplify these three lines to

root=malloc(sizeof(*root));

这篇关于C和字符串处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆