Shouldn't I delete this pointer?

Hello!

Today in my C++ programming course, I showed the teacher some code he changed to the following (Recreate stack is the important part of the code):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25

char* bottom_;
char* top;
int size_;

CStack::CStack(int n) {
    bottom_ = new char[n];
    top_ = bottom_;
    size_ = n;
}

void CStack::ReCreateStack(char n) {
    size_ += 1;
    char * tempb = new char[size_];

    std::copy(bottom_, bottom_ + (size_ - 1), tempb);
    delete [] bottom_;

    bottom_ = tempb;

    top_ = bottom_ + (size_ - 1);

    *top_ = n;
    top_++;            
}


I asked him: ''Shouldn't I delete the *tempb pointer? He said no, because it is being replaced.

I thought however that every 'new' should be deleted and nulled. In this case, temp would be created, bottom would be deleted and temp would refer to bottom. I thought the next time ReCreateStack(); is invoked, tempb should be deleted first. Is this correct?
It's important to make a distinction between:
1. "Pointer" as a variable residing on the stack. The name tempb refers to one such variable.
2. "Pointer" as an integer value that refers to a memory location. The variable tempb refers to holds such a value.
One should delete every newed pointer of the second meaning. This is incorrect:
1
2
3
4
int *foo=new int;
int *bar=foo;
delete foo;
delete bar;
foo and bar hold the same pointer. Deleting them both deletes the same pointer twice.
This is why the concept of pointer ownership is also important. An object is said to own a pointer if it assumes the responsibility of freeing it. Pointer ownership is implicitly implemented in the way you structure your code. For example, here:
1
2
3
int *foo=new int;
int *bar=foo;
delete bar;
foo transfers the ownership of its pointer to bar, and here:
1
2
3
int *foo=new int;
int *bar=foo;
delete foo;
the pointer is copied without ownership transfer.

Since bottom_ is a variable that will eventually get deleted (in CStack::~CStack(), presumably), it would be wrong to delete tempb. There's an ownership transfer on line 19.
Topic archived. No new replies allowed.