Search code examples
cpointersmallocglibcrealloc

Run-time error: *** glibc detected ***


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;
}

I expected my code to behave like this:

  1. I created a character-type memory pointer to point (at max) 15 bytes of memory using malloc.
  2. Using that character pointer, I saved 120 characters using strcpy.
  3. I resized my character pointer to now point (at max) 16 bytes.
  4. I concatenated, using strcat, 8 more characters to that memory buffer which is already holding 120 characters.
  5. Now, my character pointer should point to 128 characters and I tried to reproduce that, however, it failed for 128 characters (but printed the earlier 120 characters which was saved using strcpy).

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?


Solution

  • 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.