在释放内存时陷入无限循环

发布于 2024-12-11 08:28:38 字数 2159 浏览 0 评论 0原文

我在这里就这个问题寻求帮助 静态成员回收内存并恢复从异常

下面的程序是使用自己的 new 运算符分配内存。我必须在第五个对象分配上抛出异常,并通过释放内存来恢复(我知道这是一个奇怪的问题,但它是赋值)

我已经在这里编写了代码。分配有效,但是当我尝试调用删除(通过选项“2”)时,我陷入无限循环。

#include <iostream>
#include <cstdlib>

using namespace std;

class object
{
    int data;
    static int count;
    static void* allocatedObjects[5];
public:
    object() {  }
    void* operator new(size_t);
    void operator delete(void *);
    void static release();
    void static printCount()
    {
        cout << count << '\n';
    }
    ~object()
    {
        release();
    }
};

int object::count = 0;
void* object::allocatedObjects[5];

void* object::operator new(size_t size)
{
    if (count > 5)
        throw "Cannot allocate more than 5 objects!\n";
    void *p = malloc(size);
    allocatedObjects[count] = p;
    count++;
    return p;
}

void object::operator delete(void *p)
{
    free(p);
    count--;
}

void object::release()
{
    while (count > 0)
    {
        delete static_cast<object*> (allocatedObjects[count]);
    }
}

int main()
{
    object *o[10];
    int i = -1;
    char c = 1;
    while (c != '3')
    {
        cout << "Number of objects currently allocated : ";
        object::printCount();
        cout << "1. Allocate memory for object.\n";
        cout << "2. Deallocate memory of last object.\n";
        cout << "3. Exit.\n";
        cin >> c;
        if (c == '1')
        {
            try
            {
                i++;
                o[i] = new object;
            }
            catch (char* e)
            {
                cout <<e;
                object::release();
                i = 0;
            }
        }
        else if (c == '2' && i >= 0)
        {
            delete o[i];
            i--;
        }
    }
    return 0;
}

我做错了什么?

编辑 我已经解决了删除问题。通过摆脱析构函数。并在 main 末尾显式调用release。

但现在我的 catch 块没有捕获异常。分配 5 个对象后,抛出异常(通过调试器跟踪)但未捕获。代码中的新更改不会影响相关代​​码。

i had asked help on this question here Static member reclaiming memory and recovering from an exception

the program below is to allocate memory using own new operator. I have to throw exception on 5th object allocation and recover by freeing up memory (strange question i know, but it is assignment)

i have written the code here. allocation works, but when i try to call delete (through option '2') i get stuck in infinite loop.

#include <iostream>
#include <cstdlib>

using namespace std;

class object
{
    int data;
    static int count;
    static void* allocatedObjects[5];
public:
    object() {  }
    void* operator new(size_t);
    void operator delete(void *);
    void static release();
    void static printCount()
    {
        cout << count << '\n';
    }
    ~object()
    {
        release();
    }
};

int object::count = 0;
void* object::allocatedObjects[5];

void* object::operator new(size_t size)
{
    if (count > 5)
        throw "Cannot allocate more than 5 objects!\n";
    void *p = malloc(size);
    allocatedObjects[count] = p;
    count++;
    return p;
}

void object::operator delete(void *p)
{
    free(p);
    count--;
}

void object::release()
{
    while (count > 0)
    {
        delete static_cast<object*> (allocatedObjects[count]);
    }
}

int main()
{
    object *o[10];
    int i = -1;
    char c = 1;
    while (c != '3')
    {
        cout << "Number of objects currently allocated : ";
        object::printCount();
        cout << "1. Allocate memory for object.\n";
        cout << "2. Deallocate memory of last object.\n";
        cout << "3. Exit.\n";
        cin >> c;
        if (c == '1')
        {
            try
            {
                i++;
                o[i] = new object;
            }
            catch (char* e)
            {
                cout <<e;
                object::release();
                i = 0;
            }
        }
        else if (c == '2' && i >= 0)
        {
            delete o[i];
            i--;
        }
    }
    return 0;
}

What am i doing wrong?

EDIT
I have fixed the delete problem. By getting rid of destructor. And explicitly calling release at end of main.

But now my catch block is not catching exception. After allocating 5 objects exception is thrown (as traced through debugger) but not caught. New Changes in the code do not affect the related code.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

嗼ふ静 2024-12-18 08:28:38

发生无限循环是因为析构函数 (~object()) 在 object::operator delete() 之前被调用。您的析构函数正在尝试删除最近分配的对象,这会调用同一对象的析构函数。 operator delete() 永远不会被调用。

我不确定 allocatedObjects 在这里实现了什么,并且代码在没有它的情况下也能工作。也摆脱 release ()

更新

好的,所以需要发布(异常处理)。

不要从析构函数中调用释放。相反,在调用 free 之后,让 operator delete() 函数将 allocatedObjects 条目设置为 0(镜像 operator new( ))。 release() 函数仅在异常处理期间调用,并确保正确释放未释放的内存(即循环遍历 allocatedObjects 数组和 free非零条目,然后将它们设置为零。

The infinite loop occurs because the destructor (~object()) is called before object::operator delete(). Your destructor is attempting to delete the most recent object allocated, which calls the destructor on the same object. The operator delete() is never being called.

I'm not sure what the allocatedObjects achieves here and the code will work without it. Get rid of the release () as well.

UPDATE

OK, so there's a need for the release (exception handling).

Don't call release from the destructor. Instead, make the operator delete() function set the allocatedObjects entry to 0, after the calling free (mirroring the operator new()). The release() function is only called during exception handling and makes sure un-freed memory is freed correctly (i.e. loop through allocatedObjects array and free non-zero entries and then setting them to zero.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文