2

I'm new in C.

Here is my code:

int *i = (int *)calloc(10, sizeof(int));
i[0] = 3;
i[1] = 1;
i[2] = 2;
i[3] = 5;
printf("before: %d %d %d %d\n", i[0], i[1], i[2], i[3]);
printf("before: %d %d\n", i, (i + 3));

free(i);

printf("after: %d %d %d %d\n", i[0], i[1], i[2], i[3]);
printf("after: %d %d\n", i, (i + 3));

and output:

before: 3 1 2 5
before: 3 5
after: 0 0 2 5
after: 0 5

I used free() func. Why are not all elements of the array zero?

chqrlie
  • 131,814
  • 10
  • 121
  • 189
essnape
  • 23
  • 4
  • `free()` tells the OS that the memory is not used anymore and that the OS is free to use somewhere else. Why should `free()` set the memory to 0, what would be point of that? And why 0, why not 5 or 7? Think about that. – Pablo May 24 '20 at 18:28
  • thank you for your answer. i think, elements of array should be zero because of null. after using free(), some elements are zero but some elements are still same... is this a coincidence? or garbage value? – essnape May 24 '20 at 18:33
  • 1
    The memory no longer belongs to you after `free` so it is not the concern of the program what the memory contents are. You can't even validly check. If you want to ensure it is zeroed, you must do that yourself *before* it is `free`d. – Weather Vane May 24 '20 at 18:34
  • It is a coincidence. After freeing memory, why do you care about the value in a memory, you are not using anymore? Besides that you're code is wrong, you are not allowed to access memory you've already freed. – Pablo May 24 '20 at 18:35
  • thank you all for answers ^^ – essnape May 24 '20 at 18:43

2 Answers2

1

The data in memory maybe doesn't disappear, they can exist in the memory after freeing. But try to read from the freed memory is undefined behavior. To be sure, you can assign the pointer to NULL after freeing it (Setting variable to NULL after free).

Hitokiri
  • 3,607
  • 1
  • 9
  • 29
1

Setting the memory to 0 has some cost.

calloc already sets the memory to 0 when you call it. After free you are saying that you don't intend to use that area of memory any longer, so reading from it is a bug and can even crash your program if the page is unmapped.

Normally, for small buffers such as in your case, malloc/calloc point to a buffer managed by your libc and no system call is performed. So that is why your program did not crash immediately.

For larger buffers, normally they are allocated directly to pages requested to the OS, so when they get freed the memory is released to the OS and the pointer no longer points to any memory at all.

LtWorf
  • 7,286
  • 6
  • 31
  • 45