Back to Blog
By AriesZhou · · 1 min read

A Wild Pointer

C++

//常见错误
int *a;
*a = 12;

This code declares a pointer variable named a, then stores 12 in the space a points to.

The variable a is declared but not initialized, so the exact location a points to is unknown; where the value 12 will be stored is not yet determined.

Declaring a pointer to an integer does not create memory space for storing an integer value.

Possible outcomes of this code:

If the initial value of a is an illegal address, the assignment will fail and terminate the program. On UNIX systems, this error is usually a “segmentation fault,” “segmentation violation,” or “memory fault.” It indicates the program is attempting to access a memory location not assigned to it.

If the initial value of a happens to be a legal address, the original value at that address is overwritten by the new assignment, even though you had no intention of modifying it. Errors caused this way are hard to detect because the code triggering the error is likely unrelated to the code that operates on the modified value.

Therefore, Before dereferencing a pointer, always make sure the pointer variable has been initialized.