deleting dangling pointers

Discussion in 'C++' started by maharjun, Sep 30, 2010.

  1. maharjun

    maharjun New Member

    Joined:
    Sep 30, 2010
    Messages:
    1
    Likes Received:
    0
    Trophy Points:
    0
    if a pointer is a dangling pointer and one applies delete[] to it. is the result defined or not. i basically have the following situation

    class A
    {
    private:
    int *p;
    //other data members
    public:
    //rest of class
    }
    i intend to initialise p in the constructors. but we know that constructors are also called when the = operator is encountered(or atleast thats what i observed). so when we get the arguments from an = assignment, it is possible that p already points to some valid location and hence, while reassigning the class, would have to be deleted to avoid memory leak.

    but when the constructor is first called i.e. when object is created, at that time the pointer would not point to anything valid neither would it be NULL. hence there is a very high chance that the delete will execute even if i bracket it with an if check to check for null pointer.

    hence it would mean that i am applying the delete operator on a wild/dangling pointer. will this lead to any instability etc.?

    i know that this can be averted if i define the = operators. but im looking for ather options(if exist).

    thanks for help.
     

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice