多级指针避免野指针

xiaoxiao2021-02-28  107

必须使用一入口一出口。多出口汇合后,释放资源。

#include "stdio.h" #include "string.h" #include "stdlib.h" //释放资源函数 void freemyp(char **myp,int count) { int i=0; //如果没有申请内存 if(myp==NULL) { return; } //释放后申请的内存 for(i=0;i<count;i++) { free(myp[i]); } //释放先申请的内存 if(myp!=NULL) { free(myp); } } int spitstring2(const char* buf1,char c,char ***myp,int *num) { int ret=0; char *p=NULL,*ptem=NULL; char **mycopy=NULL; int tempnum=0; //判断传参是否正确,失败跳转 if(buf1==NULL || num==NULL || myp==NULL) { ret=-1; printf("spitstring2(const char* buf1,char c,char ***myp,int *num) error:%d\n",ret); return ret; } p=buf1; ptem=buf1; /// //检索1确定申请的行数 do{ //匹配字符串数引号 p=strchr(p,c); if(p!=NULL) { if(p-ptem>0) { tempnum++; //下一次检索条件生成 ptem=p=p+1; } } else break; }while(*p!='\0'); *num=tempnum; //申请行数 mycopy=(char**)malloc(tempnum*sizeof(char*)); //失败跳转 if(mycopy==NULL) { ret=-2; printf("spitstring2(const char* buf1,char c,int *num) malloc1 is error:%d!\n ",ret); goto END; } / //重新指向指针位置 p=buf1; ptem=buf1; tempnum=0; do{ //匹配字符串挖串 p=strchr(p,c); if(p!=NULL) { if(p-ptem>0) { mycopy[tempnum]=(char*)malloc(sizeof(char)*(p-ptem+1)); if(mycopy[tempnum]==NULL) { ret=-3; printf("spitstring2(const char* buf1,char c,int *num) malloc2 is error:%d!\n ",ret); goto END; } //挖串 strncpy(mycopy[tempnum],ptem,p-ptem); mycopy[tempnum][p-ptem]='\0'; tempnum++; //下一次检索条件生成 ptem=p=p+1; } } else break; }while(*p!='\0'); END: if(ret != 0) { freemyp(mycopy,*num); } else { *myp=mycopy; } return 0; } void main() { int ret=0,i=0; char *s="abc,dfer,vgty,hyujnb,"; //char *s=NULL; char ccmp=','; char **ps=NULL; int ncount; //挖串函数 spitstring2(s,ccmp,&ps,&ncount); //打印字符串 for(i=0;i<ncount;i++) { printf("%s\n",ps[i]); } //释放内存 free(ps); system("pause"); }

转载请注明原文地址: https://www.6miu.com/read-53960.html

最新回复(0)