Search code examples
c++assemblynew-operatorinline-assemblydelete-operator

C++ and Assembly: call 'operator new' and 'operator delete' with ASM


I am trying to call operator new and operator delete with inline ASM in Visual C++.

For example, I have a function like this:

__forceinline void __fastcall deallocate(pointer& _ptr)
{
    __asm
    {
        mov eax, dword ptr[_ptr]
        mov ecx, dword ptr[eax]
        mov dword ptr[eax], 0
        push ecx
        call operator delete
        add esp, 4
    }
}

Unfortunately, when compiling, I get these errors:

error C2414: illegal number of operands
error C2400: inline assembler syntax error in 'first operand'; found 'bad token'
error C2400: inline assembler syntax error in 'opcode'; found 'bad token'

I know this has to do with calling operator delete. If I replace it with a function like this:

__forceinline void _delete(pointer _ptr)
{
    ::operator delete(_ptr);
}

and write

call _delete

in the ASM code section, I get no errors. Can anybody tell me why and what should I do? I don't want to use this _delete function. This also happens if I try calling operator new in a similar manner. Thank you.


Solution

  • First of all, this call is ambiguous. Each type can define its own operator new and operator delete. How ASM would know which one it should call?

    Also, I think, that token with spaces is not a valid name in ASM (or even C). C++ compilers were designed to differently treat operator keyword, as the name of operator is often separated with white space. I don't think ASM knows anything about this.

    That's why you are getting this error:

    error C2414: illegal number of operands

    In ASM we separate operands with white spaces. Since you tried to call operator delete, ASM interpreted this as two operands, which is too many for call instruction.