「函數重定義錯誤」很可能是因爲你’重新使用MFC。
運行時庫不應該定義這種分配和釋放函數。
當前代碼’小號
struct MemLeakInfo
{
unsigned int addr;
unsigned int line;
unsigned int size;
unsigned char file;
};
是解精。不能保證一個unsigned int
足夠大以容納一個地址,即使它位於32位Windows中。相反,請使用intptr_t
。
此外,當前的代碼’小號
void* operator new(unsigned int Size, int Line, const char* File);
是解精。這應該是…
void* operator new(size_t Size, int Line, const char* File);
而且您需要相應的operator delete
,就像…
void* operator delete(void* p, int Line, const char* File);
,以便從失敗的構造函數調用釋放內存。這只是在非常具體的情況下才被調用。但是如果你沒有它,那麼你就有漏洞,就像MFC曾經進行調試構建一樣。
編輯:你現在提供的代碼的固定版本:
文件[微乎其微。h]:
_MINIMAL_H
無效,因爲它以下劃線開頭,後面跟着大寫字母,它是保留字。更改爲MINIMAL_H
。
- 要使用
size_t
您需要包含<stddef.h>
。
_DEBUG
不是一個標準的宏。這是一個微軟。爲此目的的標準宏(查找文檔assert
)是NDEBUG
。
#ifndef MINIMAL_H
#define MINIMAL_H
#include <stddef.h> // std::size_t
#ifndef NDEBUG
void* operator new(size_t Size, int Line, const char* File);
void* operator new[](size_t Size, int Line, const char* File);
void operator delete(void* ptr, int Line, const char* File);
void operator delete[](void* ptr, int Line, const char* File);
#endif
#ifndef NDEBUG
#define DEBUG_NEW new(__LINE__, __FILE__)
#else
#define DEBUG_NEW new
#endif
#endif //MINIMAL_H
文件[minimal.cpp]:
- 使用
malloc
你需要包括stdlib.h
。
- 當你
#define new
你’在下面的代碼重新造成new
關鍵字破壞。
- 在C中,你絕對不應該使用
malloc
的結果,而在C++中,你只能在需要的時候施放任何東西。這裏沒有這種需要。只投射面具錯誤,這不是一個好主意。
- 錯誤情況下丟失返回。對於您需要的錯誤
throw std::bad_alloc
。這是由聖潔標準’規定的這些功能。
#include "Minimal.h"
//#define new DEBUG_NEW
#ifndef NDEBUG
#include <stdlib.h> // malloc
#include <exception> // std::bad_alloc
void* operator new(size_t const size, int, const char*)
{
void* const ptr = malloc(size);
if(!ptr) { throw std::bad_alloc(); }
return ptr;
};
void* operator new[](size_t const size, int, const char*)
{
void* const ptr = malloc(size);
if(!ptr) { throw std::bad_alloc(); }
return ptr;
}
void operator delete(void* const ptr, int, const char*)
{
free(ptr);
};
void operator delete[](void* const ptr, int, const char*)
{
free(ptr);
};
#endif
是你指的是[這裏](http://www.flipcode.com/archives/How_To_Find_Memory_Leaks.shtml)的文章? – Hindol
的確,我是,謝謝。 – Unknown
你讀過了:[我應該如何編寫iso C++標準一致的自定義新的和刪除操作符](http://stackoverflow.com/questions/7194127/how-should-i-write-iso-c-standard-conformant-custom -new-and-delete-operators) –