c++ - 在 reinterpret_cast-ing 之后通过父指针调用 delete 时内存是否泄漏?

标签 c++ memory-leaks

我定义了一个父类和一个子类:

struct parent
{
    int i;

    ~parent()
    {
        printf("~parent()\n");
    }
};

struct child : public parent
{
    char value[1024*1024];

    ~child()
    {
        printf("~child()\n");
    }
};

int main()
{
    for(int i=0; i < 1000; i++)
    {
        char* child_ptr = new char[sizeof(child)]();
        parent* parent_ptr = reinterpret_cast<parent*>(child_ptr);
        delete parent_ptr;
    }

    return 0;
}

以上代码合法吗?我的意思是内存泄漏吗?我用Windows查过,内存似乎没有泄漏。

最佳答案

严格来说这是一种未定义的行为:reinterpret_cast 不是向上转换的正确行为。它有效,因为 child 指针及其 base 部分的表示可能是相同的。但是如果存在虚函数、多重继承或虚继承,或者只是一些罕见的架构,您的代码可能会失败。

记住:reinterpret_cast 几乎总是错误的。

关于c++ - 在 reinterpret_cast-ing 之后通过父指针调用 delete 时内存是否泄漏?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37918392/

相关文章:

c++ - 出现在错误列表中的 Visual C++ 的故意编译器警告?

sqlite sqlite3_close()不会释放获取的内存

sql-server - 如何跟踪数据库连接泄漏

c++ - 在 Windows x64 中检查内存泄漏的免费应用程序?

memory-management - 内存调试 : How to get locked pages information in user space/kernel space in linux

c++ - 当权限被拒绝 C++ 时,std::ofstream 不显示错误

c++ - 在 C++ 中将 TCP 服务器数据包保存到文件

c++ - CListCtrl选择

android - "Activity has leaked window that was originally added here"

c++ - _ATL_APARTMENT_THREADED 和 _ATL_FREE_THREADED 冲突