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

时间:2016-04-25 12:56:38

标签: c++ malloc heap new-operator

有没有办法知道是否使用newmalloc分配了指针变量的内存?

int* a = new int;
int* b = static_cast<int*>(malloc(sizeof *b));

//Maybe using a function?
allocatedwithnew(a); //Returns true
allocatedwithmalloc(b); //Return true

2 个答案:

答案 0 :(得分:0)

为什么不尝试使用计数器?

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

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;
}

答案 1 :(得分:-1)

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

static int newCounter = 0;
#define NEW(A) ++newCounter; new A

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