I have the following code that does not work when using both asprintf
and realloc
.
The error I am getting is:
*** glibc detected *** a.out: realloc(): invalid old size: 0x006f1430 ***
Based on what I have researched it looks like when I use asprintf
it is overwriting some memory that realloc
uses. This doesn't make sense to me since asprintf
is supposed to be safe and dynamically allocate using the appropriate string length. Not using asprintf
causes the program to run fine, but I need the functionality of asprintf
for my project.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
int ifCount = 1;
int stringCount = 1;
char** IFs = NULL;
//Broken code
char* message;
asprintf(&message, "Hello: %d", stringCount);
//Working code, but not the alternative I want to take
//char* message = "Hello";
IFs = (char**) realloc(IFs, sizeof(char*) * ifCount);
IFs[ifCount - 1] = (char*) realloc(IFs[ifCount - 1], sizeof(char) * strlen(message));
strcpy(IFs[ifCount - 1], message);
printf("Message: %s\n", message);
printf("Copy: %s\n", IFs[ifCount - 1]);
free(message);
}