Greetings. There is a certain function that receives the hash sum of the file (exe) and writes it to a file. It is launched in the stream, but the application from where it starts is crashing. I would like to know how to properly run the function in the stream so that the application does not crash.

void initialize() { string buffer; thread t(calclulateHash, ref(buffer)); t.detach(); } BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved) { switch (fdwReason) { case DLL_PROCESS_ATTACH: { initialize(); break; } } return true; } 
  • 2
    What is a ref(buffer) ? Do you understand what this line does? - Pavel Mayorov
  • Have you tried writing the same thing in a regular console application? What does it have to do with DllMain? - Pavel Mayorov

2 answers 2

Thus, as you do, you can not do. In DllMain cannot be started (or synchronized) .

Take out the start of the stream in a separate function and call it not from DllMain , but from another place.


One of the possible causes of the problem is the synchronization of all DllMain calls: each of its calls is waiting for the others to finish. If you start a stream, it results in a recursive call with the DLL_THREAD_ATTACH flag (not PROCESS ), which immediately leads to problems.

DllMain is special; very limited function, the principles applied to ordinary functions do not work here.


Well, the signature of the function calculateHash interesting, of course.

  • You can expand the idea, it is not clear the restriction on the launch of streams from DllMain - Vladimir Gamalyan
  • @VladimirGamalian: This is a limitation of the operating system. - VladD
  • Well, in the same place, "should", CreateThread is actually quite twitching (although bad practice, yes). (Creating a thread can not be synchronized with it, but it is risky.) - Vladimir Gamalyan
  • @VladimirGamalian: Well, that said “no, there can be problems”, and that's just the problem :-) - VladD
  • @VladimirGamalian: Surely the standard library performs some kind of synchronization, which is strictly prohibited in DllMain . There is also no direct call to CreateThread , with which problems can only be. - VladD

Roughly speaking, local variable

 string buffer; 

passed to the stream by reference (thanks to std::ref ):

 thread t(calclulateHash, ref(buffer)); 

which thread is disconnected and executed and, as I understand it, then it tries to write to buffer

 t.detach(); 

which is no longer there, because the function in which it is declared is long over ...

Why would you even consider something that you do not use?