cmemory-managementvariable-assignment

My C code works fine but crashes right before the end (0xC0000374)


So I'm learning to code (in C) for a few months now and I'm focusing here on memory allocation.

My code is very simple, everything works, and yet at the end, it doesn't return a 0 but instead I get a -1073740940 (0xC0000374) which, I noticed, have something to do with memory allocation (lol). And seriously I don't know how to correct it.

Here it is :

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

int main()
{

 char* chaine1 = (char*)malloc(10*sizeof(char));
 char* chaine2 = (char*)malloc(10*sizeof(char));

 if(chaine1 == NULL || chaine2 == NULL)
    return -2;

 strcpy(chaine1, "Salut les");
 strcpy(chaine2, " codeurs!");

 printf("Chaine 1: %s\n", chaine1);
 printf("Chaine 2: %s\n", chaine2);

 int taille1 = strlen(chaine1);
 int taille2 = strlen(chaine2);

 char* tmp_chaine = (char*)malloc(sizeof(char)*10);

 if(tmp_chaine == NULL)
    return -2;

 strcpy(tmp_chaine, chaine1);

 realloc(chaine1, sizeof(char)*(taille1+taille2+1));

 for(int i = 0; i <= taille1; i++)
    chaine1[i] = tmp_chaine[i];

 for(int i = 0; i <= taille2; i++)
    chaine1[taille1+i] = chaine2[i];

printf("%s", chaine1);

return 0;
}

I noticed that when I try to free my strings, the program crashes before the end, but that's all I could figure out.

(I know the code has nothing optimized, please don't yell at me :( )


Solution

  • Code 0xC0000374 is STATUS_HEAP_CORRUPTION. The heap corruption happens because realloc() is used improperly.

    realloc(chaine1, sizeof(char)*(taille1+taille2+1));
    

    The returned new pointer is ignored, chaine1 pointer is unchanged and points to an old and freed memory location. Further lines use that wrong memory location and corrupt the heap.

    You can allocate the required size a few lines above with malloc() without using realloc().

    If you still wish to try realloc() then it should be

    char* new_chaine1 = realloc(chaine1, taille1+taille2+1);
    if (new_chaine1) {
      chaine1 = new_chaine1;
      new_chaine1 = NULL;
    } else {
      // handle the reallocation error
    }
    

    The code exhibits memory leaks in main() without free().

    Further notes. sizeof(char) is odd, always 1, can be omitted. (char*) cast from void* is not needed at malloc().