pointers from heap and instances from stack C++

84 views Asked by At

My purpose is to determine if I should deallocate using delete a variable to a pointer stored in a linked list...

I had the idea to consider that any pointer allocated in the heap will be strictly superior to the first "new" used... and that any variable stored in the stack at any kevel of any procedure call will be inferior to the first pointer allocated with "new"...

I tried :

void main()

     { int A;
       int *b = new int;

       cout << &A << '\t' << b;
     }

on my computer, it outputs :

0x0019FE9C     0x0236542C

that is b > a .... so looks like correct on Windows 10...

Is this an illusion or really correct and portable ?

1

There are 1 answers

10
463035818_is_not_an_ai On

Your strategy is flawed for several reasons.

Even if you could reliably compare two pointer that do not point to element of the same array (you cannot) there is following issue:

#include <iostream>
    
int main() {
    int *b = new int;
    int *c = b;    
    std::cout << b << '\t' << c << '\n';

}

b and c have the same value. If you use only the value of the pointer to decide whether to use delete or not, then you either delete both or neither of them.

If you delete both you invoke undefined behavior. If you delete neither of them you have a leak.

The fundamental issue here is false expectations about raw pointers. Raw pointers point somewhere, and that's it. Hence, if you need to manage lifetime of some object then a raw pointer alone cannot do that.

Do not use raw owning pointers. Use std::list, std::unique_ptr and/or other facilities the standard library offers. In rare cases you need to write your own lifetime managing code, then it must be concentrated to a simple RAII class that manages the lifetime of an object but nothing else.

Some buzzwords for further reading: rule of zero, smart pointers, ownership, no raw owning pointers, RAII.