内存泄漏跟踪

memory leak trace

本文关键字:跟踪 泄漏 内存      更新时间:2023-10-16

>我已经覆盖了我的运算符 new[] 作为

void* operator new[](std::size_t sz, const char *file, int line)
{
    void* mem = malloc(sz);
    if(mem == 0){
            printf("Could not allocate the desired memory, the new operator failsn");
            std::abort();
        }
    printf("Allocation has been done!n");
    printf("Allocation has been done! In %s, line #%i, %p[%i]n", file, line, mem, sz);
    return mem;
}
#define DEBUG_NEW2 new[](__FILE__, __LINE__)
#define new[] DEBUG_NEW2

我的程序主要使用这种类型的新运算符,这就是为什么我更关心它。但是,编译器给我"宏名称 [-Werror] 后缺少空格"错误消息。我试图玩弄"#define 新的[]DEBUG_NEW2"。在某些情况下,它可以编译正常,但是我不会被覆盖new[]。

这里的问题是以#define new[]开头的行

您正在尝试创建名为 new[] 的宏。

首先,这是非法的,因为宏名称必须是有效的标识符,这意味着它只包含字母、下划线、数字,并且不能以数字开头。

其次,您正在尝试为关键字赋予新的含义。这是不允许的,这意味着您的程序无效或提供未定义的行为。

无需添加这样的宏即可重载运算符 new[]。实际上,您需要做的就是在所需范围内声明一个带有签名void* operator new[](size_t)的函数,它将自动用于数组分配。