Attempting to free p
here invokes undefined behavior - you're only allowed to free what you malloc (or calloc, or realloc, or strdup). In this case, you're free-ing a pointer to a stack variable, a
, which is not allowed.
The same applies to dereferencing *q
- the value in q
is uninitialized, so dereferencing it causes undefined behavior as well. Strictly speaking, p = q
is undefined* as well, but in practice simply copying the value of an uninitialized variable tends not to cause too much of a problem in and of itself (just don't expect the value to be meaningful).
When you invoke undefined behavior, anything can happen - this includes, but is not limited to:
- Crashing right away
- Crashing later in some unrelated code
- Corrupting some data without crashing
- Corrupting some data on disk that you thought was safe
- Contacting your backup server and corrupting the backups too
- Allowing the hacker who triggered the bug control over your computer
- Summoning demons through your nasal passages
- Any combination of the above
- On occasion, nothing at all.
The compiler is not required to give any sort of helpful error message, although it may do so in some cases.
In short, don't do it, but don't expect it to break in any one particular way if you do. These kinds of things have a funny way of breaking in a way that looks like bugs in a completely different part of your code.
* - per C99 6.2.6.1, if the C implementation has trap representations for pointer types, it is possible for the unspecified initial value for a variable to be a trap representation, at which point reading it via the q
lvalue invokes undefined behavior.