C++ Memory Management – Is the Use of Pointer Variables a Memory Overhead?

cpointers

In languages like C and C++, while using pointers to variables we need one more memory location to store that address. So isn't this a memory overhead? How is this compensated? Are pointers used in time critical low memory applications?

Best Answer

Actually, the overhead does not really lie in the extra 4 or 8 bytes needed to store the pointer. Most times pointers are used for dynamic memory allocation, meaning that we invoke a function to allocate a block of memory, and this function returns to us a pointer which points to that block of memory. This new block in and of itself represents a considerable overhead.

Now, you don't have to engage in memory allocation in order to use a pointer: You can have an array of int declared statically or on the stack, and you can use a pointer instead of an index to visit the ints, and it is all very nice and simple and efficient. No memory allocation needed, and the pointer will usually occupy exactly as much space in memory as an integer index would.

Also, as Joshua Taylor reminds us in a comment, pointers are used to pass something by reference. E.g., struct foo f; init_foo(&f); would allocate f on the stack and then call init_foo() with a pointer to that struct. That's very common. (Just be careful not to pass those pointers "upward".) In C++ you might see this being done with a "reference" (foo&) instead of a pointer, but references are nothing but pointers that you may not alter, and they occupy the same amount of memory.

But the main reason why pointers are used is for dynamic memory allocation, and this is done in order to solve problems that could not be solved otherwise. Here is a simplistic example: Imagine you want to read the entire contents of a file. Where are you going to store them? If you try with a fixed-size buffer, then you will only be able to read files that are not longer than that buffer. But by using memory allocation, you can allocate as much memory as necessary to read the file, and then proceed to read it.

Also, C++ is an object-oriented language, and there are certain aspects of OOP like abstraction that are only achievable using pointers. Even languages like Java and C# make extensive use of pointers, they just don't allow you to directly manipulate the pointers, so as to prevent you from doing dangerous stuff with them, but still, these languages only begin to make sense once you have realized that behind the scenes everything is done using pointers.

So, pointers are not only used in time-critical, low-memory applications, they are used everywhere.

Related Topic