免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 2781 | 回复: 4

[应用] 新手遇到malloc出现段错误问题???? [复制链接]

论坛徽章:
0
发表于 2015-08-05 15:01 |显示全部楼层
直接代码,子函数第一调用正常执行,第二次调用出现段错误,新手实在不解,请求大神指导

变量定义
int tel_num;
struct st_tel *tel_p = NULL;
主函数多次调用
    tel_add(&tel_p, &tel_num);
子函数
int tel_add(struct st_tel **my_tel, int *tnum)                           
{
    (*my_tel) = realloc(*my_tel, (sizeof(struct st_tel)) * (*tnum + 1));
    if(NULL == *my_tel){                                             
         printf("realloc is error\n");                                   
         return -1;                                                  
     }                                                                  
     my_tel[*tnum]->name = NULL;                                      
     //出现段错误                                                        
     my_tel[*tnum]->name = malloc(strlen(argv[1]) + 1);                                
     if(NULL == (my_tel[*tnum]->name)){                                    
        printf("malloc is error\n");                                   
         return -1;                                                      
     }                                                                     
     strcpy(my_tel[*tnum]->name, argv[1]);                        
     strcpy(my_tel[*tnum]->num , argv[2]);   
     return 0;   
}                        

论坛徽章:
1
IT运维版块每日发帖之星
日期:2015-09-15 06:20:00
发表于 2015-09-18 10:48 |显示全部楼层
请你把struct st_tel 的详细 定义写出来,你结构体里的 name 字段是 字符串数组 还是指针。 如果 name 是指针,   my_tel[*tnum]->name = NULL;  这句话应该是多月的,只有在开辟空间之后。你才可以对该空间进行赋值操作。我的理解是这样的,多指教。

论坛徽章:
1
IT运维版块每日发帖之星
日期:2015-09-15 06:20:00
发表于 2015-09-18 10:48 |显示全部楼层
本帖最后由 yangchao1117 于 2015-09-18 10:49 编辑

请你把struct st_tel 的详细 定义写出来,你结构体里的 name 字段是 字符串数组 还是指针。 如果 name 是指针,   my_tel[*tnum]->name = NULL;  这句话应该是多余的,只有在开辟空间之后。你才可以对该空间进行赋值操作。我的理解是这样的,多指教。

论坛徽章:
0
发表于 2015-09-19 16:59 |显示全部楼层
我也学一下~~~~~·

论坛徽章:
0
发表于 2015-09-29 15:09 |显示全部楼层
    my_tel[*tnum]->name = (typeof( my_tel[*tnum]->name ))malloc(strlen(argv[1]) + 1);     

.......
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP