我可以测试变量是否已使用 new 或 malloc 分配吗?



有没有办法知道指针变量的内存是使用 new 还是malloc分配的?

int* a = new int;
int* b = static_cast<int*>(malloc(sizeof *b));
//Maybe using a function?
allocatedwithnew(a); //Returns true
allocatedwithmalloc(b); //Return true

你为什么不试试计数器?

据我了解,您的代码如下所示:

if(ConditionA) {
  A obj = new A;
} else {
  A obj = malloc(sizeof(int));
}

你可以做这样的事情:

#include <iostream>
#include <stdlib.h>
using namespace std;
struct A{
  int ab;
  bool createdByNew;
};
int main()
{
    int CountNewAllocations=0;
    int CountMallocAllocations=0;
    bool Condition=true; // this will be set to appropriate value
    A *obj = NULL;
    if(Condition) {
      obj = new A;
      obj->createdByNew=true;
      CountNewAllocations++;
    } else {
      obj = (A*) malloc(sizeof(A));
      obj->createdByNew=false;
      CountMallocAllocations++;
    }
    // ... use the object
    if(obj!=NULL) {
      if(obj->createdByNew) {
        delete obj;
        CountNewAllocations--;
      } else {
        free(obj);
        CountMallocAllocations--;
      }
    }
    return 0;
}

您可以使用将 new 替换为 NEW 的定义,然后将定义设置为

static int newCounter = 0;
#define NEW(A) ++newCounter; new A
static int mallocCounter = 0;
#define MALLOC(A) ++malloCounter; malloc A

最新更新