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?
The data in memory maybe doesn't disappear, they can exist in the memory after free
ing. But try to read from the freed memory is undefined behavior. To be sure, you can assign the pointer to NULL
after free
ing it (Setting variable to NULL after free).