The below program takes input a sentence, an old word, and a new word.
The objective is to 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); <-------------------------------
}
After executing, i am getting the error as: 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: ========
The programs works when i comment the statement:
free(ptr);
see here: http://ideone.com/fr34H
Why i am getting error when i try to free() the memory allocated on heap?
You messed up the internal information kept by
mallocand it detected it when at the next operations (which was the free). Here’s the reason:In this context the sizeof evaluates to the size of the integer on your platform: almost surely less than what you want. So when you write to
ptr, after 4 or 8 bytes you’ll step outside the allocated area and all bets are off.Side note: it’s largely a matter of taste but you should probably stop casting the value returned by
malloc.