A problem that is about calloc and free functions in C

Viewed 366

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?

2 Answers

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

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.

Related