1

Is there a way to write to a file within a replaced global operator new?

// simple operator new replacment
void* operator new(std::size_t bytes) {
    std::ofstream log{"log.txt"};
    log << bytes << " bytes allocated\n";
    return std::malloc(bytes);
}

std::ofstream uses new, creating an infinite loop.

A-n-t-h-o-n-y
  • 410
  • 6
  • 14
  • It's usually not a good idea, but you might be able to work around it if you know *where* `std::ofstream` uses `new`. Does it do it in the constructor or when opening the file? Then you can just open the file before the first `new` is called. If it happens in the `<<` operator then perhaps uses fixed-size strings (arrays) and use `snprintf` to format the output and `write` the output to the file? – Some programmer dude Jan 30 '18 at 04:43

1 Answers1

0

You can overload the operator but for specific parameters, I mean not the global one, Here an example for a class called student :

 void * operator new(size_t size)
{
    cout<< "Overloading new operator with size: " << size << endl;
    void * p = ::new student(); 
    //void * p = malloc(size); will also work fine

    return p;
}

you can find more details Here

Ali Safaya
  • 56
  • 9