0

I was trying to learn the memory management of c.

I allocated the memory for

1. char** a
2. char** b
3. char* b[0] ~ b[99]

and

I freed the memory for

1. char** a
2. char* b[0] ~ b[99]
3. char** b

However, I got an error at the line33, which is free(b[0])

Why does it produces invalid next size free (fast)?

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main()
{

  char** a = (char**)malloc(100 * sizeof(char*));
  a[0] = "Hello Again!";



  char** b = (char**)malloc(100 * sizeof(char*));
  int i = 0;
  for(i = 0; i < 100; i++){
    b[i] = (char*)malloc(10 * sizeof(char));
  }

  strcpy(b[0], *a);

  free(a);

  printf("%s", b[0]);

  for(i = 0; i < 100; i++){
      free(b[i]);
  }

  free(b);
  return 0;

}
Sathish
  • 3,740
  • 1
  • 17
  • 28
Peter Hwang
  • 971
  • 1
  • 12
  • 25

5 Answers5

1

The string "Hello Again!" is 13 characters long (including the terminating \0).

The memory you allocate for it is not enough (you allocate just 10 chars), so when calling strcpy you are overwriting past the allocated memory, and probably overwriting the memory location used by the library to keep track of allocations.

The next time that the library will try and use the information stored there, it finds that it is inconsistent, so it aborts with the error you mentioned. That is only one of the many messages that the library can print if it is able to find any such discrepancy.

In general, do not rely on the library flagging those errors for you: in this case you were "lucky" that the info were corrupted in a recognizable way. If you are unlucky, your program might just exhibit undefined behavior.

Marco Leogrande
  • 8,050
  • 4
  • 30
  • 48
  • Technically, it's not a question of *might* exhibit undefined behavior - it *is* undefined behavior. This includes the error OP encountered. – Drew McGowen Aug 14 '14 at 05:24
0

For each b[i], you only allocate space for 10 chars, but the strcpy copies the string "Hello Again!", which is certainly more than 10 chars. This is undefined behavior.

Drew McGowen
  • 11,471
  • 1
  • 31
  • 57
0

When you execute this line,

strcpy(b[0], *a);

you are writing over memory that you were not supposed to use. That leads to undefined behavior.

Some environments store useful information at the end of the allocated block of memory. By writing over that memory, you have destroyed that useful information.

R Sahu
  • 204,454
  • 14
  • 159
  • 270
0

The error is this line:

strcpy(b[0], *a);

You allocate 10 bytes for b[0], but you copy 13 bytes, thereby writing beyond the end of the allocated memory.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
0

It's a buffer overrun because strlen(a[0]) + 1 > 10. You need to allocate more than 10 characters for b[0], specifically at least strlen(a[0]) + 1.

David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490