下面的程序接受输入a sentence
,an old word
和 a new word
。
目标是replace all the occurrences old word with the new word
。
int countOccurrence(char* sen,char* word) //counts occurrences of old word
{
int count=0,i,k,len1,len2;
len1=strlen(sen);
len2=strlen(word);
for(i=0;i<len1-len2+1;)
{
k=0;
while(word[k] && sen[k+i]==word[k])
k++;
if(k==len2 && sen[k+i]==' ' || sen[k+i]=='\0')
{
count++;
i+=len2;
}
else ++i;
}
return count;
}
void replace(char* sen,char* oldword,char* newword)
{
int count,len1,len2,len3,i,top=-1,k;
char *ptr;
count=countOccurrence(sen,oldword);
if(!count) return;
len1=strlen(sen);
len2=strlen(oldword);
len3=strlen(newword);
ptr=(char*)malloc(sizeof(len1+count*(len3-len2)+1));
for(i=0;i<len1-len2+1;)
{
k=0;
while(oldword[k] && sen[k+i]==oldword[k])
k++;
if(k==len2 && sen[k+i]==' ' || sen[k+i]=='\0')
{
for(k=0;newword[k];++k)
ptr[++top]=newword[k];
i+=len2;
}
else
{
ptr[++top]=sen[i];
++i;
}
}
ptr[++top]='\0';
strcpy(sen,ptr);
free(ptr); <-------------------------------
}
执行后,我收到错误:http: //ideone.com/mh3X1
*** glibc detected *** ./prog: free(): invalid next size (fast): 0x08f49008 ***
======= Backtrace: =========
/lib/libc.so.6[0xb75fcfd4]
/lib/libc.so.6(cfree+0x9c)[0xb75fe87c]
./prog[0x8048834]
./prog[0x80484c1]
======= Memory map: ========
当我评论声明时,程序有效:
free(ptr);
见这里:http: //ideone.com/fr34H
为什么当我尝试释放()堆上分配的内存时出现错误?