简体   繁体   中英

C++ Custom memory allocation link error in VS2012

I get the following linker error when I try to override the default memory allocation functions in VS2012:

1>Main.obj : error LNK2005: "void * __cdecl operator new(unsigned int)" (??2@YAPAXI@Z) already defined in MSVCRTD.lib(MSVCR110D.dll) 1>Main.obj : error LNK2005: "void __cdecl operator delete(void *)" (??3@YAXPAX@Z) already defined in MSVCRTD.lib(MSVCR110D.dll) 1>c:\\users\\documents\\visual studio 2012\\Projects\\CustomMemoryAllocator\\Debug\\CustomMemoryAllocator.exe : fatal error LNK1169: one or more multiply defined symbols found

Here is my code (I get no intellisense errors):

#include <iostream>

using namespace std;

void *operator new(size_t size){
    if(void *mem = malloc(size)){
        cout << "allocated memory" << endl;
        return mem;
    }
    else{
        throw bad_alloc();
    }
}

void operator delete(void* mem) throw() {
    cout << "deleting" << endl;
    free(mem);
}

int main(){
    cout << "test";
    int* a = new int(4);
    delete a;
    int b = 0;
    cin >> b;
}

Could someone please help?

Libraries not getting linked in correct order

Trying adding at top of your file

#pragma comment(linker, "/nodefaultlib:libc.lib")
#pragma comment(linker, "/nodefaultlib:libcd.lib")

Else follow these instructions.

Try using a DLL instead of static linking the libraries. Go to project properties / C++ / Code Generation / Runtime Library and pick the DLL option.

Windows calls a DLL or EXE a module. A module is not allowed to multiply define a symbol, but two different modules used by one process can define the same symbol. When using a DLL, operator new() is defined in both your and the MSVC module which causes no error.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM