Why does freeing allocated memory with the free() function give me invalid next size error?

I'm trying to free the allocated memory but I get an error: free(): invalid next size (fast): 0x0000000001008010 ***

Here's my code:

int main(int argc, char *argv[]) {
char *text_p;        // do not change

char TEXT_P[] = "malloc try 1.";
char REALLOC[] = "--realloc";
text_p = (char*)malloc(10);
if (text_p == NULL) {
   printf("Memory Allocation Failed.");
   exit(1);
}
strncpy(text_p, TEXT_P, strlen(TEXT_P)+1);
printf("Final Copied String using malloc: '%s'\n", text_p);

// reallocate memory
text_p = (char*)realloc(text_p, 15);
if (text_p == NULL) {
   printf("Memory Allocation Failed.");
   exit(1);
}
strncat(text_p, REALLOC, strlen(REALLOC)+1);
printf("'%s'", text_p);


free (text_p);
text_p = NULL;

This is the error I get: Error


strncpy(text_p, TEXT_P, strlen(TEXT_P)+1); corrupts memory because strlen(TEXT_P)+1 is 14 but you only allocated 10 bytes.

That is the wrong way to use strncpy. The third argument should be number of bytes available in the destination (or less), not the length of the second argument. And you need to ensure the destination in null terminated, because strncpy will not add a terminating null character if it runs into the length limit.

The message “invalid next size” is free reporting it has found its memory to be corrupted.