Ivaylo Valchev
Ivaylo Valchev

Reputation: 10425

Unexplained exception thrown by calling deallocate from a custom allocator

Visual Studio doesn't explain anything to me, it just breaks and sends me conveniently to the operator delete implementation....

Why is it unable to deallocate?

#include <iostream>

template<typename T>
struct Allocator
{
    using size_type = std::size_t;
    using pointer = T*;

    pointer allocate(size_type n)
    {
        return static_cast<pointer>(::operator new(n * sizeof(T)));
    }

    void deallocate(pointer p)
    {
        ::operator delete((void*)p);
    }
};

int main()
{
    Allocator<int> al;

    int a = 5;
    int* p = al.allocate(1);
    p = &a;
    al.deallocate(p);
}

Upvotes: 0

Views: 85

Answers (1)

Sam Varshavchik
Sam Varshavchik

Reputation: 118445

You are deallocating something else other than what you allocated.

You are allocating, assigning the result to p, then immediately overwrite the result with some other, random pointer, which you attempt to deallocate.

The reason for your crash should be obvious.

P.S. As far as Visual Studio goes, it correctly brings you to the line where the illegal memory access occured. Sadly, the state of modern technology is not yet to the point where you also get a detailed explanation of what exactly went wrong, at that point.

Upvotes: 3

Related Questions