0

I have some code that looks like this.

#include <iostream>
#include <string>
void* operator new(std::size_t n){
    std::cout << "[Allocating " << n << "bytes] ";
    return malloc(n);
}

void operator delete(void* pointer) throw() {
    free(pointer);
}

int main(){

    for(int i = 0; i < 24; i++){
        std::cout << i << ": " << std::string(i, '=') << std::endl;
    }

}

this compiles and runs using gcc compiler and also runs when using msvc compiler with the flag /MT or /MTd set. however if I set the flag to /MDd or /MD The program crashes. It seems to be stuck in a recursion inside the new operator. Why doesn't this happen when compiling and linking against LIBCMT.lib which as I can tell from Microsoft docs is the difference between /MT and /MD.

1
  • Why is your operator delete marked throw and your operator new not? Commented Sep 20, 2019 at 23:12

1 Answer 1

1

You are using std::couts operator << inside your new replacement function. This operator easily might call new itself to perform some allocation, in turn, calling your new replacement, which would call <<, and so on, and so forth.

You should be careful about what you do in those functions. If you want to see how they are called, you can use some preallocated structures and log with them (or simply increment a global counter).

The reason why it happens with one set of flags but not the another is likely due to different allocation strategies employed by << based on those flags. Those would be private to implementation and you shouldn't rely on them.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for this answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.