在下面的简短程序中:当没有valgrind运行时,会调用重载的全局new运算符,而valgrind根本不调用它,而是显然调用valgrind的全局new运算符。我的问题是:我们如何让valgrind调用应用程序的全局新/删除? (valgrind 3.13.0; OS Linux,Ubuntu 14.04.5 LTS,x86_64)(应用程序的重载运算符可以将内存标记为使用VALGRIND_MEMPOOL_ALLOC / VALGRIND_MEMPOOL_FREE宏,但我们无法实现) (编辑:使用valgrind 3.10.1调用全局新运算符)
#include <malloc.h>
#include <new>
void* operator new (size_t size_i) throw (std::bad_alloc)
{
fprintf(stderr,"new %d (operator new (size_t size_i) throw (std::bad_alloc))\n", __LINE__);
return malloc(size_i);
}
void* operator new (size_t size_i, const std::nothrow_t& nothrow_value) throw()
{
fprintf(stderr,"new %d (operator new (size_t size_i, const std::nothrow_t& nothrow_value) throw())\n", __LINE__);
return malloc(size_i);
}
void* operator new[] (size_t size_i) throw (std::bad_alloc)
{
fprintf(stderr,"new %d (operator new[] (size_t size_i) throw (std::bad_alloc)) \n", __LINE__);
return malloc(size_i);
}
void* operator new[] (size_t size_i, const std::nothrow_t& nothrow_value) throw()
{
fprintf(stderr,"new %d (operator new[] (size_t size_i, const std::nothrow_t& nothrow_value) throw()) \n", __LINE__);
return malloc(size_i);
}
void operator delete (void* p_i) throw()
{
fprintf(stderr, "delete %d (operator delete (void* p_i) throw())\n",__LINE__);
free(p_i);
}
void operator delete (void* p_i, const std::nothrow_t& nothrow_constant) throw()
{
fprintf(stderr, "delete %d\n",__LINE__);
free(p_i);
}
void operator delete[] (void* p_i) throw()
{
fprintf(stderr, "delete %d\n",__LINE__);
free(p_i);
}
void operator delete[] (void* p_i, const std::nothrow_t& nothrow_constant) throw()
{
fprintf(stderr, "delete %d\n",__LINE__);
free(p_i);
}
#include <stdio.h>
main()
{
fprintf(stderr, "ku !\n");
char * a = new char[123];
delete [] a;
int * b = new int();
delete b;
return 0;
}
现在编译它
gcc -g valg.cpp -lstdc++
在没有valgrind的情况下运行它
$ ./a.out
ku !
new 19 (operator new[] (size_t size_i) throw (std::bad_alloc))
delete 43
new 6 (operator new (size_t size_i) throw (std::bad_alloc))
delete 31 (operator delete (void* p_i) throw())
使用valgrind全局运算符new不会被调用。
valgrind ./a.out
==24181== Memcheck, a memory error detector
==24181== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==24181== Using Valgrind-3.13.0 and LibVEX; rerun with -h for copyright info
==24181== Command: ./a.out
==24181==
ku !
==24181==
==24181== HEAP SUMMARY:
==24181== in use at exit: 0 bytes in 0 blocks
==24181== total heap usage: 2 allocs, 2 frees, 127 bytes allocated
==24181==
==24181== All heap blocks were freed -- no leaks are possible
==24181==
==24181== For counts of detected and suppressed errors, rerun with: -v
==24181== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)