0

I wrote simple program, there is it:

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

int main()
{
    int *p = (int *)calloc(6, sizeof(int));
    p[0] = 10;
    p[1] = 20;
    p[2] = 30;
    p[3] = 40;
    p[4] = 50;
    p[5] = 60;
    p[6] = 70;
    p[7] = 80;
    p[8] = 90;
    p[9] = 100;
    printf("hello world %d\n", p[9]);
    free(p);
}

It not works and gives us error:

malloc(): corrupted top size
Aborted (core dumped)

This is logical because we added 6 ints to array. But now it's time for f*****g magic, i wrote this:

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

int main()
{
    int *p = (int *)calloc(7, sizeof(int));
    p[0] = 10;
    p[1] = 20;
    p[2] = 30;
    p[3] = 40;
    p[4] = 50;
    p[5] = 60;
    p[6] = 70;
    p[7] = 80;
    p[8] = 90;
    p[9] = 100;
    printf("hello world %d\n", p[9]);
    free(p);
}

And it works. We added 7 ints to array and it can contain 10 ints, how so? And the last question is why it:

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

int main()
{
    int *p = (int *)calloc(7, sizeof(int));
    p[0] = 10;
    p[1] = 20;
    p[2] = 30;
    p[3] = 40;
    p[4] = 50;
    free(p);
    p[5] = 60;
    p[6] = 70;
    p[7] = 80;
    p[8] = 90;
    p[9] = 100;
    printf("hello world %d\n", p[9]);
}

works?

Gohryt
  • 353
  • 1
  • 4
  • 10
  • You're facing an [undefined behaviour](https://en.wikipedia.org/wiki/Undefined_behavior) (UB). In that case, anything can happen, so don't try to find a repetable logic, it would be ineffective the day after – Mathieu Feb 02 '21 at 10:15

1 Answers1

0

Reading an array beyond its last element is Undefined Behaviour in C. It means that anything can happen. Your software may crash or nothing wrong may happen at all... It doesn't make much sense to wonder why your program crashes for an array of 6 and doesn't for an array of 7. This is what Undefined means. If you are curious you may want to look at the assembly code and how the heap is implemented on your system but it is kinda pointless.

The function free is only modifying some indexes in the heap (memory reserved for dynamic memory allocation). It doesn't erase memory itself. It is of course Undefined Behaviour to access an array after having freed it, but if you're lucky nothing will happen.

EDIT: the comments have been posted while I was writing this answer.

Guillaume Petitjean
  • 2,408
  • 1
  • 21
  • 47