tags:

views:

164

answers:

5

I'm reading through an example in primer and something which it talks about is not happening. Specifically, any implicit shallow copy is supposed to copy over the address of a pointer, not just the value of what is being pointed to (thus the same memory address). However, each of the pos properties are pointing to two different memory addresses (so I am able to change the value of one without affecting the other). What am I doing wrong?

Header

#include "stdafx.h"
#include <iostream>

class Yak
{
public:
    int hour;
    char * pos;
    const Yak & toz(const Yak & yk);
    Yak();
};

END HEADER

using namespace std;
const Yak & Yak:: toz(const Yak & yk)
{
    return *this;
}

Yak::Yak()
{
    pos = new char[20];

}

int _tmain(int argc, _TCHAR* argv[])
{
    Yak tom;
    tom.pos="Hi";

    Yak blak = tom.toz(tom);


    cout << &blak.pos << endl;
    cout << &tom.pos << endl;


    system("pause");
    return 0;
}
+11  A: 

You're printing the addresses of the pointers, not the address of the string they're pointing to:

cout << &blak.pos << endl;
cout << &tom.pos << endl;

They are two different pointers, so their addresses differ. However, they point to the same string:

cout << static_cast<void*>(blak.pos) << endl;
cout << static_cast<void*>(tom.pos) << endl;

(Note that cast static_cast<void*>(tom.pos). As Aaron pointed out in a comment, it is necessary because when outputting a char* will through operator<<, the stream library will assume the character pointed to to be the first character of a zero-terminated string. Outputting a void*, OTOH, will output the address.)


Note that there is more wrong with your code. Here

Yak tom;

You are creating a new object. Its constructor allocates 20 characters, and stores their address in tom.pos. In the very next line

tom.pos="Hi";

you are assigning the address of a string literal to tom.pos, thereby discarding the address of the bytes you allocated, effectively leaking that memory.

Also note that Yak has no destructor, so even if you don't discard the 20 characters that way, when tom goes out of scope, tom.pos will be destroyed and thus the address of those 20 bytes lost.

However, due to your missing copy constructor, when you copy a Yak object, you end up with two of them having their pos element pointing to the same allocated memory. When they go out of scope, they'd both try to delete that memory, which is fatal.


To cut this short: Use std::string. It's much easier. Get a grip on the basics, using safe features of the language like the std::string, the containers of the stdandard library, smart pointers. Once you feel sure with these, tackle manual memory management.

However, keep in mind that I, doing C++ for about 15 years, consider manual resource management (memory is but one resource) error-prone and try to avoid it. If I have to do it, I hide each resource behind an object managing it - effectively falling back to automatic memory management. :)


Which "primer" is this you're reading? Lippmann's C++ Primer? If so, which edition? I'd be surprised if a recent edition of Lippmann's book would let you lose onto dynamic memory without first showing your the tools to tackle this and how to use them.

sbi
+1 Faster as usual :]
PeterK
@sbi: I think the OP wanted `blak` to be a shallow copy of `tom` --- hence the printing of addresses.
Jacob
This is on the right track certainly, but cout << blak.pos << endl;is missing the point slightly. This code will print the strings, whereas we want to print the pointers themselves to confirm they are identical. The following works for me: cout << (void*) blak.pos << endl; cout << (void*) tom.pos << endl;
Aaron McDaid
@Aaron: Dammit! I completely missed that! I've added the cast. Thanks for pointing it out.
sbi
Alright thanks very much. Prata's primer. He did go over it, I've just been slightly cramming and forgot a couple things but these posts make me go over my mistakes so I appreciate it.
Ilya
+2  A: 

Unless i'm missing something, it seems you are printing out the address of variable pos, but not the address to which they both point to. The addresses of both pos are different, but the pointers should be the same.

PeterK
+1  A: 

The code does not make a lot of sense.

The toz method takes a Yak but does nothing with it. Why? In fact, what is toz supposed to do, anyway?

tom.pos = "Hi" does not copy Hi into the new char[20] array that you allocate in the constructor. Instead it replaces the pos pointer with a pointer to a static const char array containing "Hi\0". You would need to use strcpy.

Zan Lynx
A: 

Your code has a memory leak in it. You are allocating 20 characters on construction and have pos point to the allocated memory. However you are then pointing pos at the memory containing "Hi" without deleting the memory first.

In any case, pos is a member variable of type char *. Each instance of Yak is going to have its own unique pos. Because pos is a pointer, however, it's possible that they are pointing to the same block of memory (and this is the case in your example).

What you are printing out is the address of the pos variable which is of type char *, and not the address of the memory it is pointing to, which is of type char. Remember that a pointer is a variable like any other, it has an address and a value (and that value, in the case of a pointer, is an address).

Niki Yoshiuchi
A: 

If you want blak to be a shallow copy of tom, try the following instead of using your function toz:

Yak *blak = &tom;

// Note the use of -> ; also, &blak->pos will work
cout << &(blak->pos) << endl; 
cout << &tom.pos << endl;

Now, blak merely points to tom --- it has nothing else associated with it.

Also, there are two other issues with your code:

pos = new char[20];

You are allocating memory here which has not been freed when you're done with the Yak object --- this will lead to memory leaks (unless you plan to free it elsewhere). If the use of pos ends with the use of the Yak object it's associated with (e.g.tom) then I recommend adding delete pos; to the destructor of Yak. Or as sbi suggested, use std::string.

tom.pos = "Hi";

You're assigning it to a string literal. This means that pos will be stuck to Hi which is actually a read-only section in memory. You cannot change the string stored in pos, so I don't think this what you intended. Therefore, allocating 20 bytes in the beginning to pos seems pointless.

Again, I recommend using string.

Jacob
That doesn't copy `tom`, it aliases it. Changing `blak->hour` affects `tom.hour`, which would not be true of a shallow copy.
Ben Voigt