Theory
Common mistakes
Pointer bugs are dangerous because the program often crashes somewhere other than where the bug is.
Common mistakes
- A forgotten
&.swap(x, y)instead ofswap(&x, &y):makes pointer from integer without a cast. Where a function writes, pass the address. - An uninitialised pointer.
int *p; *p = 5;writes who knows where. A pointer always gets a value straight away: an address orNULL. - Dereferencing
NULL.*pwhenp == NULLcrashes (0xC0000005on Windows,Segmentation faulton Linux). A function taking a pointer checksassert(p != NULL). - The address of a local variable.
return &x;from a function givesfunction returns address of local variable. The variable disappears with the function. int *p, q;Hereqis a plainint, not a pointer: the star belongs only top. Write one declaration per line.&instead of&&.if (a & b)tests bits,if (a && b)whether both are true.2 & 1is 0, although both numbers are "true".- Shifting an
int.1 << 31is undefined behaviour (UBSan:left shift of 1 by 31 places). For bits useunsignedand1u. - The size of
long. 4 bytes on Windows, 8 on Linux: what worked in CLion may give a different result in CI. Find the size withsizeof.