You are here:

C++/pointer address and object address

Advertisement


Question
Hi,

I want to make sure I understand correctly. are the following four points correct?

1/ The line 7 print the address of the variable foo
2/ The line 8 print the address of the object pointed by the variable foo (it is different from the address of the variable foo itself)
3/ The address of the variable foo is re-used each time
4/ The address of the object pointed by the variable foo is NOT re-used

------------------------------
#include <iostream>
using namespace std;

class Foo {};

int main() {
for(int i=0;i<10;i++) {
Foo* foo = new Foo();
cout<<"var address: "<<&foo<<endl; // line 7
cout<<"obj address: "<<foo<<endl; // line 8
}
}
-----------------------------

Thanks,
lzzzz



-------------------------
Followup To
Question -
Hi,

With the following small program, I try to print the address of the pointer foo and the address of the object of type Foo, I found 10 addresses of the pointer foo are the same, I thought they should be the same only if I declare the foo before the for loop, could you clear this for me?

Thanks,
lzzzz

------------------------------
#include <iostream>
using namespace std;

class Foo {};

int main() {
for(int i=0;i<10;i++) {
Foo* foo = new Foo();
cout<<"var address: "<<&foo<<endl; // print pointer foo's address
cout<<"obj address: "<<foo<<endl; // print object Foo's address
}
}
-----------------------------
Answer -
Well the foo object - a pointer to Foo type - is (notionally) created and destroyed each time around the loop. Of course, as pointers do not have any construction or destruction actions this means only that foo gets allocated an address on the stack and initialised each time around the loop with the result of the new operation. After the first time around the loop the stack slot used by the last foo is available - because it was destroyed at the end of the previous iteration. The compiler knows this so just re-uses the same address each time.

It also means that you can never delete any but the last Foo created as you have lost any reference to all but the last Foo - i.e. you have a memory (and possibly other resources) leak.

If you need to create 10 objects and keep references to them store the pointers in a collection - array, std::vector, std::list etc. I'll leave you to work out the details.  

Answer
Sounds about right to me (although you do not have lines 7 and 8 on separate lines in the code as it arrived in my inbox they are all 1 long line!).

Remember, new allocates from the heap and _you_ are responsible for ensuring the memory is deallocated by calling delete passing the pointer to the object (or objects in the case of delete []) to be deleted.

As you do not delete the objects allocated by new each use of new allocates a new block, at a different address.

The pointer returned by new you keep in foo, a local variable allocated on the stack frame of the main function call context. The allocation of these is handled for you by the compiler, which as I explained in the original answer is clever enough to know that the memory slot for each new foo for each iteration of the loop (other than the first) is available because it destroyed the foo it created on the previous iteration at the end of the previous iteration. There is only ever one foo in existence at any one time, so the compiler can reuse the memory slot for each one. Think of each foo as a guest in a hotel. Each time around the loop a foo checks in and then checks out. Having checked out the room it occupied (the memory address on the stack) is now empty and can be used for another guest the foo checking in the next time around...

Hope this helps.

C++

All Answers


Answers by Expert:


Ask Experts

Volunteer


Ralph McArdell

Expertise

I am a software developer with more than 15 years C++ experience and over 25 years experience developing a wide variety of applications for Windows NT/2000/XP, UNIX, Linux and other platforms. I can help with basic to advanced C++, C (although I do not write just-C much if at all these days so maybe ask in the C section about purely C matters), software development and many platform specific and system development problems.

Experience

My career started in the mid 1980s working as a batch process operator for the now defunct Inner London Education Authority, working on Prime mini computers. I then moved into the role of Programmer / Analyst, also on the Primes, then into technical support and finally into the micro computing section, using a variety of 16 and 8 bit machines. Following the demise of the ILEA I worked for a small company, now gone, called Hodos. I worked on a part task train simulator using C and the Intel DVI (Digital Video Interactive) - the hardware based predecessor to Indeo. Other projects included a CGI based train simulator (different goals to the first), and various other projects in C and Visual Basic (er, version 1 that is). When Hodos went into receivership I went freelance and finally managed to start working in C++. I initially had contracts working on train simulators (surprise) and multimedia - I worked on many of the Dorling Kindersley CD-ROM titles and wrote the screensaver games for the Wallace and Gromit Cracking Animator CD. My more recent contracts have been more traditionally IT based, working predominately in C++ on MS Windows NT, 2000. XP, Linux and UN*X. These projects have had wide ranging additional skill sets including system analysis and design, databases and SQL in various guises, C#, client server and remoting, cross porting applications between platforms and various client development processes. I have an interest in the development of the C++ core language and libraries and try to keep up with at least some of the papers on the ISO C++ Standard Committee site at http://www.open-std.org/jtc1/sc22/wg21/.

Education/Credentials

©2016 About.com. All rights reserved.