linux C语言:*** glibc detected *** ./control: free():invalid pointer:
前言
今天遇到了一个问题,折腾好久才找到问题原因,永远不要理想化,各种困难都会浮现的,我们只需要不骄不躁,一定可以解决所有问题。
问题代码
我们先来看一下问题代码部分吧。
static char *control_process(char *verb[],char *noun[],char *result)
{
int verbOpcode = 0; //verb Opcode index
int nounOpcode = 0; //noun Opcode index
char *Matchverb = (char *)malloc(40*sizeof(char));
char *Matchnoun = (char *)malloc(40*sizeof(char));
char *Playfile = (char *)malloc(sizeof(char)*40);
int index1 = 0;
printf("enter the control_process \n\n");
for(index1 =1; index1 <37;index1++)
{
Matchverb = mystrstr1(result,verb[index1]);
if(Matchverb != NULL)
{
verbOpcode = index1;
break;
}else
{
verbOpcode = 0;
}
}
int index2 = 0;
for(index2 = 1;index2 <29;index2++)
{
Matchnoun = mystrstr1(result,noun[index2]);
if(Matchnoun != NULL)
{
nounOpcode = index2;
break;
}else
{
nounOpcode=0;
}
}
printf("achieve the verb and noun deal \n\n");
sprintf(Playfile,"/mnt/card/1%02d2%02d",verbOpcode,nounOpcode);
printf("play file is %s \n\n",Playfile);
free(Matchverb);
free(Matchnoun);
return Playfile;
}
解决问题
就是这段代码,一直报错,初看确实看不到什么问题,为此我加了很多打印,最后确定问题就发生在 free(Matchverb);free(Matchnoun);这两句话,下面就讲一个一知识点,为什么free发生异常了呢?
我们在使用malloc分配内存后,指针变量获取到了地址。但是在程序中我们又给指针变量重新赋值了,因此地址发生了变化,此时我再次使用free()来释放,已经不是原来malloc分配的内存地址了,因此这就是指针地址非法。
修改方法
为了防止地址发生变化,我可以在定义两个指针变量保存malloc分配初地址,然后在释放之前将初地址重新赋值回去,这样就完美解决了。
static char *control_process(char *verb[],char *noun[],char *result)
{
int verbOpcode = 0; //verb Opcode index
int nounOpcode = 0; //noun Opcode index
char *Matchverb = (char *)malloc(40*sizeof(char));
char *Matchnoun = (char *)malloc(40*sizeof(char));
char *Playfile = (char *)malloc(sizeof(char)*40);
char *p1 = Matchverb;
char *p2 = Matchnoun;
int index1 = 0;
printf("enter the control_process \n\n");
for(index1 =1; index1 <37;index1++)
{
Matchverb = mystrstr1(result,verb[index1]);
if(Matchverb != NULL)
{
verbOpcode = index1;
break;
}else
{
verbOpcode = 0;
}
}
int index2 = 0;
for(index2 = 1;index2 <29;index2++)
{
Matchnoun = mystrstr1(result,noun[index2]);
if(Matchnoun != NULL)
{
nounOpcode = index2;
break;
}else
{
nounOpcode=0;
}
}
printf("achieve the verb and noun deal \n\n");
sprintf(Playfile,"/mnt/card/1%02d2%02d",verbOpcode,nounOpcode);
printf("play file is %s \n\n",Playfile);
Matchverb = p1;
Matchnoun = p2;
free(Matchverb);
free(Matchnoun);
return Playfile;
}
完美解决问题,这是我想到的办法,如果你有更好的办法,欢迎讨论,互相学习!!!!
还没有评论,来说两句吧...