I have this piece of faulty code
#include <stdlib.h>
int main()
{
int arr[] = { 1,2,3,5, 9, 0, 9, 3, -88, -64 };
int *count;
free(count);
return 0;
}
which works as expected and gives a munmap_chunk(): invalid pointer
error. But when remove the line where arr
is declared in main I don't see any error and I do not understand why. In both the cases I am freeing a wild pointer, so why is the error being shown in the former? I am using onlinegdb's C compiler(which is gcc afaik).
CodePudding user response:
A “wild pointer” is not a thing. That is, there is no such thing that is a pointer that has the property of being wild.
When free(count)
is called, the behavior is not defined by the C standard, due to a special rule about using uninitialized automatic objects. However, if the C implementation does call free
for this code, it passes some value for the argument.
If somebody says that is a “wild” value, they do not mean any particular value or any particular kind of value is passed. They mean the value is not controlled. Because it is not controlled, it could be zero, it could be the address of arr
, it could be the address of something on the stack, it could be the address of main
, it could be the address of nothing at all, and it could be a value that is not valid as an address at all.
In whatever experiment you tried, when the int arr
declaration was present, some value was passed to free
that resulted in the error message you saw. And when the declaration was not present, some other value was passed to free
that did not result in an error message. That value that was passed may have been merely happenstance of what happened to be left on the stack or in a program register after the program initialization that precedes execution of main
. Removing the declaration may have incidentally changed what happened to be left in memory or registers or may have changed which memory or registers the compiler used in place of count
when calling free
.
Asking the compiler to show the assembly code for the two programs (with GCC’s -S
switch) might show more about what happened.