CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 11 of 11

Thread: Wanings logging system when trying to access freed memory?

  1. #1
    Join Date
    Jul 2017
    Location
    Greece
    Posts
    114

    Wanings logging system when trying to access freed memory?

    I was wondering if I could create a logging system to use for identifying if my code is trying to delete or access freed memory.
    This is how it could work.

    Code:
    LOGGER(my_object, "Warning: this object's memory is not owned by you.");
    delete my_object;
    LOGGER_PUSH(my_object);
    .
    .
    .
    //somewhere else in the code using the same object.
    LOGGER(my_object, "Warning: this object's memory is not owned by you.");
    my_object->doSomeStuff();
    Basically, every time I delete an object, I'm pushing the memory address to a data structure LOGGER_PUSH. Then using LOGGER I'm searching inside this data structure and if the memory address exists then it means that this object has been freed.

    Now let's say that a new object is being created and gets a mem address that has been pushed into the logger (old mem that was deleted before is now being reused). In order to fix that I have to remove that address from the data structure like this:

    Code:
    new_obj = new SomeCoolClass();
    LOGGER_POP_IF_EXISTS(new_obj);
    Do you think this will work? It would be really cool If I could know in which line a mem address is freed and I'm trying to access it. Imagine how much work it will save me on debbuging and searching one by one the execution from the stack trace to actually find where this memory was freed or why it was null.

    Also is it possible to have a situation like the one below?
    Lets say i have two objects a and b. a has mem address a=3000 and then it gets deleted deleted_addresses[3000]. Then b is being instantiated with b=3000 and now deleted_addresses[]. In this situation, even that a has been deleted it happens that is pointing in an address that is currently being used in the same process but its actually another object. And what happens if a is the same type as b? What bugs can been caused by this? Is it even possible? Am I over-thinking this too much? I know that when you delete a pointer is a good practice to set it to null, but when you have a lot of copies of that address inside your system you can't possible find every last of them and set them to null...
    Last edited by babaliaris; September 2nd, 2019 at 03:26 PM.

  2. #2
    Arjay's Avatar
    Arjay is offline Moderator / EX MS MVP Power Poster
    Join Date
    Aug 2004
    Posts
    13,318

    Re: Wanings logging system when trying to access freed memory?

    The approach I would take is to leverage C++ as much as possible and use encapsulation where a class instance is responsilble for deleting and nulling out any pointers to child objects it creates. I would avoid situations where I'm not 'in control' of pointers and using smart pointers may help.

  3. #3
    Join Date
    Jul 2017
    Location
    Greece
    Posts
    114

    Re: Wanings logging system when trying to access freed memory?

    Quote Originally Posted by Arjay View Post
    The approach I would take is to leverage C++ as much as possible and use encapsulation where a class instance is responsilble for deleting and nulling out any pointers to child objects it creates. I would avoid situations where I'm not 'in control' of pointers and using smart pointers may help.
    Can you show me with an example? Because I'm struggling understanding what you mean. Thank you.

  4. #4
    2kaud's Avatar
    2kaud is offline Super Moderator Power Poster
    Join Date
    Dec 2012
    Location
    England
    Posts
    7,193

    Re: Wanings logging system when trying to access freed memory?

    Look up RAII in your c++ books or on the internet. Eg see https://en.wikipedia.org/wiki/Resour...initialization
    All advice is offered in good faith only. All my code is tested (unless stated explicitly otherwise) with the latest version of Microsoft Visual Studio (using the supported features of the latest standard) and is offered as examples only - not as production quality. I cannot offer advice regarding any other c/c++ compiler/IDE or incompatibilities with VS. You are ultimately responsible for the effects of your programs and the integrity of the machines they run on. Anything I post, code snippets, advice, etc is licensed as Public Domain https://creativecommons.org/publicdomain/zero/1.0/ and can be used without reference or acknowledgement. Also note that I only provide advice and guidance via the forums - and not via private messages!

    C++17 Compiler: Microsoft VS2019 (16.7.0)

  5. #5
    Join Date
    Jul 2017
    Location
    Greece
    Posts
    114

    Re: Wanings logging system when trying to access freed memory?

    Is this what you mean?

    Code:
    #include <iostream>
    #include <vector>
    
    using namespace std;
    
    
    class Person
    {
    
        public:
        std::string m_name;
    
        public:
        Person(std::string name, Person **src) : m_name(name)
        {
            m_references.push_back(src);
        }
    
        ~Person()
        {
            for (Person **p : m_references)
                *p = NULL;
        }
    
        void print()
        {
            std::cout << m_name << std::endl;
        }
    
        Person *get(Person **src)
        {
            m_references.push_back(src);
            return this;
        }
    
        private:
        std::vector<Person **> m_references;
    
    };
    
    
    
    
    int main()
    {
        Person *a = new Person("Nick", &a);
        Person *b, *c;
       
        //Get references of a and keep track the actual variable which stores that reference.
        b = a->get(&b);
        c = a->get(&c);
    
        a->print();
        b->print();
        c->print();
    
        delete a;
        
        //All of them must be null at this point (after deletion of a)
        std::cout << "a: " << a << std::endl;
        std::cout << "b: " << b << std::endl;
        std::cout << "c: " << c << std::endl;
    
    }
    I believe this is a really good strategy to be aware that an object has been freed. Also, notice that I will make this work only for debug mode using macros.
    Last edited by babaliaris; September 4th, 2019 at 11:42 AM.

  6. #6
    Join Date
    Jul 2017
    Location
    Greece
    Posts
    114

    Re: Wanings logging system when trying to access freed memory?

    I just noticed that this will cause a problem... What if those references go out of scope??? Then, when the deletion of the object happens, I will try to set NULL references that have gone out of scope BOOM memory access violation

    I need a mechanism, that when those references go out of scope, they will be removed by the m_references vector.

    This probably is easy. A wrapper template class lets name it Pointer<type> . When it goes out of scope, it also removes itself from the actual m_references of the object that is wrappping.
    Last edited by babaliaris; September 4th, 2019 at 11:58 AM.

  7. #7
    2kaud's Avatar
    2kaud is offline Super Moderator Power Poster
    Join Date
    Dec 2012
    Location
    England
    Posts
    7,193

    Re: Wanings logging system when trying to access freed memory?

    re RAII. I was meaning something like this:

    Code:
    #include <cstring>
    #include <iostream>
    using namespace std;
    
    class Person {
    public:
    	Person() = default;
    
    	Person(const char* const nam) : name(strcpy(new char[strlen(nam) + 1], nam)) {}
    
    	~Person() { delete[] name; }
    
    	const char* operator()() { return name; }
    
    private:
    	char* name = nullptr;
    };
    
    int main()
    {
    	Person per("My name");
    
    	cout << per() << endl;
    }
    Obviously, this is a contrived example as you wouldn't do this in practice (use a std::string). But the principle is that all memory allocation/delete is handled by the class constructor(s)/destructor. That way you know memory is allocated/deleted OK as it is only allocated by a constructor and deleted automatically by the destructor when the class object goes out of scope. No need to have new/delete anywhere in your code outside of a class constructor/destructor. if you do need memory allocation outside of the class for some reason, then use managed pointers (unique_ptr & shared_ptr as needed). These are effectively a simple RAII implementation around new/delete.
    All advice is offered in good faith only. All my code is tested (unless stated explicitly otherwise) with the latest version of Microsoft Visual Studio (using the supported features of the latest standard) and is offered as examples only - not as production quality. I cannot offer advice regarding any other c/c++ compiler/IDE or incompatibilities with VS. You are ultimately responsible for the effects of your programs and the integrity of the machines they run on. Anything I post, code snippets, advice, etc is licensed as Public Domain https://creativecommons.org/publicdomain/zero/1.0/ and can be used without reference or acknowledgement. Also note that I only provide advice and guidance via the forums - and not via private messages!

    C++17 Compiler: Microsoft VS2019 (16.7.0)

  8. #8
    Join Date
    Jul 2017
    Location
    Greece
    Posts
    114

    Re: Wanings logging system when trying to access freed memory?

    This is basically a unique_ptr implementation, right? I see now! Incredible! Finally, I learned why smart pointers can be handy.

    If I'm not wrong, shared ptrs are implemented with reference counting?

    Well, then this is what I will use. I won't use c++ <memory> smart pointers, because I want them to do some more stuff, like keeping track when a deletion occurred (__LINE and __FILE__).

    But now I get the idea, thank you so much!!!

  9. #9
    Join Date
    Jul 2017
    Location
    Greece
    Posts
    114

    Re: Wanings logging system when trying to access freed memory?

    Actually, can I inherit smart pointers to extend them?

  10. #10
    2kaud's Avatar
    2kaud is offline Super Moderator Power Poster
    Join Date
    Dec 2012
    Location
    England
    Posts
    7,193

    Re: Wanings logging system when trying to access freed memory?

    shared ptrs are implemented with reference counting?
    Yes. The memory is only released when the reference count becomes 0 on a destructor.
    All advice is offered in good faith only. All my code is tested (unless stated explicitly otherwise) with the latest version of Microsoft Visual Studio (using the supported features of the latest standard) and is offered as examples only - not as production quality. I cannot offer advice regarding any other c/c++ compiler/IDE or incompatibilities with VS. You are ultimately responsible for the effects of your programs and the integrity of the machines they run on. Anything I post, code snippets, advice, etc is licensed as Public Domain https://creativecommons.org/publicdomain/zero/1.0/ and can be used without reference or acknowledgement. Also note that I only provide advice and guidance via the forums - and not via private messages!

    C++17 Compiler: Microsoft VS2019 (16.7.0)

  11. #11
    Arjay's Avatar
    Arjay is offline Moderator / EX MS MVP Power Poster
    Join Date
    Aug 2004
    Posts
    13,318

    Re: Wanings logging system when trying to access freed memory?

    Quote Originally Posted by babaliaris View Post
    Is this what you mean?
    I believe this is a really good strategy to be aware that an object has been freed. Also, notice that I will make this work only for debug mode using macros.
    If you code with encapsulation and make your classes responsible for cleaning up child objects they've allocated, then you don't need to know when an object is deleted because you'll end up with a hierarchy of objects rather than a flat structure of many objects. If you have a hierarchy with each object responsible for cleaning up, and you only have a few top-level objects, then cleanup is very simple - just delete the top-level object(s).

    If you are allocating objects all over the place, and are having trouble tracking them, then in my opinion, you are doing it wrong.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  


Windows Mobile Development Center


Click Here to Expand Forum to Full Width




On-Demand Webinars (sponsored)