I was experimenting random things to know more about malloc, realloc and free and how they behave when they are used together.
I will include the code and my idea what I was trying to do.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(void)
{
char *str;
/* Initial memory allocation */
str = (char *) malloc(15);
strcpy(str, "63tczfqV4nqB2YnH9iFJbGvGyyDkvK341rrj0G0mo1PEYniOVHejVIFIQnJzHSSMRbuyGMCZ4M5HFMV4y1q4QgYqyxp2XkTjxaolKTkaw1r25S2Emz061tw1");
printf("String = %s, Address = %u\n", str, *str);
/* Reallocating memory */
str = (char *) realloc(str,16);
strcat(str, "12345678");
printf("String = %s, Address = %u\n", str, *str);
free(str);
return 0;
}
The exact error was this:
***** glibc detected *** ./a.out: realloc(): invalid next size: 0x0000000001690010 *****
and the console hung on this, i.e., it never moved past realloc line I suppose?
Let's look at the first two lines of your code:
str = (char *) malloc(15);
strcpy(str, "63tczfqV4nqB2YnH9iFJbGvGyyDkvK341rrj0G0mo1PEYniOVHejVIFIQnJzHSSMRbuyGMCZ4M5HFMV4y1q4QgYqyxp2XkTjxaolKTkaw1r25S2Emz061tw1");
At this point, you have broken the rules of the C language. strcpy
will write past the end of str
which causes undefined behavior.
Everything that happens after this point is kinda up in the air.