Advice Pointers

what are the list of precautions that one should take while using "raw" pointers.Putting the question other way round , what are the mistakes that people make when using raw pointers.

I know I can go with smart pointers but people did manage to write code efficiently for huge softwares in legacy C and/or C++ using raw pointers .What are their techniques and what do they stick to so that they make minimum(if not huge) amount of mistakes.

Thanks!

what are the mistakes that people make when using raw pointers.
0) Using raw pointers. Seriously, there is rarely need for them.

1) Not initializating pointers to point to actual object or null. There is nothing worse than to have pointer pointing to arbitrary memory.
2) Not assigning null to pointers after object they point to is destroyed.
3) Not testing pointers for null. Note that testing should happens before any use. Even calling const member functions (it is UB)
4) In general messing up ownership/accessing object destroyed through other pointer.
5) Forgetting to free dynamically allocated object.
6) Creating a pointe to the stack and forgetting about lifetime of said object
6a) Returning a pointer to local variable.
7) Building up levels of indirection. If you ever see something like ***p in your code, I have bad news for you.
8) Incorrect address arithmetics on pointers. Remember, everything that does not transform pointer to array element to pointer to other element of the same array or one-past-the-end element is UB
9) Casting pointers to other pointer type. It is really easy to get an UB here.
10) Incorrectliy casting pointers to integer type. No, neither unsigned int nor uint32_t are created to hold pointers.

I probably missed, like, 10 more points, but it is good for beginning
Last edited on
Topic archived. No new replies allowed.