Search code examples
cheap-corruption

Heap Corruption Detected after Normal block (#155) in C


I have a piece of code like this:

#include <string.h>
#include <stdlib.h>
#include <stdio.h>

int main()
{
    char array[10000];
    char *newArray=NULL;
    int j=0;
    int k;
    while(gets_s(array))
    {
       int length=strlen(array);
       newArray=(char *)realloc(NULL,length*sizeof(char));
       for(int i=length-1;i>=0;i--)
       {
           if(array[i]==' '||i==0)
           {
               if(i==0)
                   i--;
               k=i+1;
               while(array[k]!=NULL&&array[k]!=' ')
               {
                   newArray[j++]=array[k++];
               }
               newArray[j++]=' ';
           }
       }
       newArray[j]='\0';
       printf(newArray);
       free(newArray);
    }
}

What I am trying to do is that I want to reverse the string as I continuously input the string.

For example, I input: "this is a dog", the result will return: "dog a is this", and I want to continue to input another string and found the error:

"HEAP CORRUPTION DETECTED: after Normal block (#155) at 0x004CAF38
CRT detected that the application wrote to memory after end of heap buffer"

What's causing this?


Solution

  • You are not allocating enough memory in your newarray to allot for the end of string terminating character:

    newArray=(char *)realloc(NULL,length*sizeof(char));
    

    Later you are setting:

    newArray[j]='\0';
    

    where j exceeds the memory size by 1.

    Change to:

    newArray=(char *)realloc(NULL,length*sizeof(char) + 1);
    

    and

      newArray[j-1]='\0'
    

    Also need to reset j.