C Programming
C++ Programming

What are the drawbacks of using pointers in C?

User Avatar
Wiki User
June 27, 2012 4:06PM

The main drawback is that they're a bit more difficult to use than references. References always point to valid data (they can never be NULL), but pointers may be NULL or may point to arbitrary data, including other pointers. The programmer is therefore entirely responsible for ensuring their pointers point at valid data before they can actually use that data; the compiler is not able to foretell the runtime condition of a pointer. When there is a choice between using a reference or a pointer to a reference, the reference is the preferred choice. But if there's any chance the reference could be NULL, a pointer must be used instead.

If memory is allocated to a pointer (using malloc or new), the programmer is responsible for releasing that memory, otherwise a memory leak will occur. By contrast, references will fall from scope automatically. However, a danger here is that the programmer may point to a reference that falls from scope, leaving a dangling pointer. Any attempt to access that pointer may result in a runtime error (if not, it is a "time-bomb" which may crash the program at a later time, with no indication as to the cause).

Pointers can also be used to "rove" within the data of an object, a structure or an array. While this is a powerful feature, great care must be taken to ensure the data is valid. For instance, overrunning a data buffer is a common source of errors and can lead to exploitation by hackers who may be able to inject arbitrary code into your code, with all the same privileges of the original code. This is particularly dangerous when functions accept pointers to unchecked data buffers which can overwrite the return address of the function to point at the "infected" code in the buffer.

While there are drawbacks to using pointers, with appropriate usage they make it possible to produce more efficient code than might otherwise be possible with references alone. Thus the only real drawback is when they are used inappropriately.