Search code examples
callocationrealloc

c realloc - memory not allocated as i set it


i build a function that will delete a word in text that i wrote, the function works,

but from some reason the memory is more then i allocated so after i finish it print the new string without the word but with symbols and gibberish.

please help me understand why and how could i fix it, thank you.

when i debugged the memory change soon as i used this :

newStr[k] = str[i];



char * newText(char * word, char *str)
{
 int count = 0, indexS = -1,indexE = -1;
 char *newStr = (char*)calloc(1,sizeof(char));
 int w = 0, k = 0,i,i2;
 if(strlen(word) > strlen(str))
     printf("Error: the word dosent exist");
 else
 {
     for (i = 0; i < strlen(str); i++)
     {
         if (str[i] != word[w])
         {
             newStr[k] = str[i];
             k++;
             newStr = realloc(newStr, k + 1);
         }
         else
         {
             i2 = i;
             while (str[i2] != ' ' && str[i2] != '\0')
             {
                 if (str[i2] == word[w])
                 {
                     count++;
                     w++;
                     i2++;
                 }
                 else
                 {
                     count = -1;
                     break;
                 }

             }
             if (strlen(word) == count)
             {
                 i = i2;
                 if (str != '\0') i++; // space
             }
             else
             {
                 newStr[k] = str[i];
                 k++;
                 newStr = realloc(newStr, k + 1);
             }
             count = 0;
             w = 0;
         }
    }
 }
 str[k] = '\0';
 return newStr;
}

Solution

  • You are appending '\0' character to the wrong string at the end before you return:

    str[k] = '\0';
    

    make it:

    newStr[k] = '\0';