Sign in to follow this  
Jarwulf

Pointers and Memory Management

Recommended Posts

There are two nagging things in C++ I've never seemed to fully understand over the course of time. Memory management (especially) and use of pointers (to a lesser extent). I understand the technical details of both but in the course of my work (from hello worlds to 3d Ogre levels with players and moving robots) I've never come across a situation where you couldn't easily get around using them or fully understood what situations they should be used in. I would have thought I would learn in time but C++ learning resources no matter the source seem to ignore both concepts for beginners and then take them for granted for more advanced users.

1. So what are the advantages of pointers over arrays? What situations would you use pointers in?

2. The main tools for memory management in C++ are new and delete right? Obviously you don't need to use them at all in simple applications so what situations would you use them in and how would you know when a program becames complicated enough to justify it?

Share this post


Link to post
Share on other sites
Quote:
So what are the advantages of pointers over arrays? What situations would you use pointers in?
I say this every time someone says they don't get pointers. Build a linked list. Then come back here if you still don't understand why pointers exist. This one exercise is enlightening.

Quote:
The main tools for memory management in C++ are new and delete right?
No. Or rather, you're focusing on two very specific things. There's always some memory allocation and deallocation going on. One type of memory allocation is dynamic allocation, for which the operators new and delete are used. Memory management is a bit more general than those two operators.

When do you dynamically allocate memory? One reason is large resources. Operating systems like Windows will provide limited stack space. Large blocks of memory need to be dynamically requested. If you try to allocate something like an array of a few million integers, you won't succeed unless you allocate dynamically.

Or if you don't know how much to allocate until runtime. Like reading from a file. How much data to store? You have no idea until you actually read the file. So there is some dynamic management of memory here, to acquire, and then reallocate when you need to store more data.

When is dynamic allocation justified? When you need it.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this