Minimizing Pointer Usage in C for Bug Prevention

bugcpointers

I think most people would agree that pointers are a major source of bugs in C programs (if not the greatest source of bugs). Other languages drop pointers entirely for this reason. When working in C, then, would it be best to avoid using pointers whenever practicable? For example, I recently wrote a function like this:

void split (char *record, char *delim,
            int numfields, int fieldmax,
            char result[numfields][fieldmax]);

While not as versatile as a dynamically allocated variable, in that it requires the programmer to know the number of fields in advance and anything over fieldmax is truncated (which is sometimes acceptable), it eliminates the need for memory management, and the potential for memory corruption. I think this is a pretty good trade, but I was wondering what the opinions of other programmers on this were.

Best Answer

Other languages don't "drop pointers entirely," they just restrict what you can do with them, give them a syntax that looks like non-pointer variables, handle some operations on them behind the scenes, and call them something else, like a reference or object. If you ever have to make a distinction between assigning a copy of something or not, you are dealing with pointers.

With the exception of programming paradigms that pass everything by copy, with obvious performance implications, the use of pointers is unavoidable in all but the simplest of programs. By all means, use stack variables where it makes sense, but if you try to avoid pointers too much, you will introduce a whole different breed of potential bugs.

Related Topic