2

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);
}
Mike
  • 47,263
  • 29
  • 113
  • 177
  • Don't change the name of your post to include `(answered)` on your question when it's been solved here. Just click the check mark by the answer that solves your problem – Mike Nov 12 '12 at 15:43

2 Answers2

5

This:

IFs[ifCount - 1] = (char*) realloc(IFs[ifCount - 1], sizeof(char) * strlen(message));

is passing a non-initialized pointer to realloc(), which is the cause of the error.

Also:

  1. Remember that strings need termination space, the above is allocating strlen(message) characters which is 1 too few. This will cause strcpy() to do a buffer overrun when copying.
  2. Please remember that realloc(), like all functions that allocate heap memory, can fail. This is true for asprintf() too.
  3. Don't cast the return value of realloc() in C.
  4. Avoid sizeof (char), since it's always 1 it adds very little value to the code.
Community
  • 1
  • 1
unwind
  • 391,730
  • 64
  • 469
  • 606
0

Instead of using realloc with a NULL or uninitialized first argument, just use malloc to begin with.

If the realloc call is necessary in the IFs[ifCount - 1] = (char*) realloc(...) call, then on the previous line, use calloc instead - that will at least zero out the allocated memory so that realloc is given a proper NULL pointer.

prprcupofcoffee
  • 2,950
  • 16
  • 20
  • 1
    No, using `calloc()`, which initializes to all-bits-zero, is not valid for pointers. There's no guarantee that all-bits-zero is the proper in-memory pattern for a `NULL` pointer. – unwind Nov 12 '12 at 15:30
  • Thanks for the clarification - appreciated. – prprcupofcoffee Nov 12 '12 at 15:41