How to prevent crash when invoke fwrite with different file in multi-thread?

Ace Wang 1 Reputation point
2023-01-09T10:14:48.307+00:00

My app keep crash when fwirte without way to reproduce.

My code is like this:

FILE *fp = fopen(tempFileName.c_str(), "wb");  
if (fp) {  
	fwrite(jsonString.c_str(), 1, jsonString.length(), fp);  
	fclose(fp);  
  
	remove(_filename.c_str());  
	// move temp file to overwitten original one;  
	rename(tempFileName.c_str(), _filename.c_str());  
  

crash stack like this:

CrashRpt!Ordinal10+0x70fd  
CrashRpt!Ordinal10+0x4224  
CrashRpt!Ordinal10+0x5064  
ucrtbase!invalid_parameter+0x145  
ucrtbase!invalid_parameter_noinfo+0x9  
ucrtbase!_isatty+0x3afa0  
ucrtbase!__acrt_stdio_begin_temporary_buffering_nolock+0x19  
ucrtbase!<lambda_96f4279ff90247a4c5c5d9824f56f8c1>::operator()+0x20  
ucrtbase!__crt_seh_guarded_call<unsigned __int64>::operator()<<lambda_bdbcead8b570fa3d5ec6d9679862a6e5>,<lambda_96f4279ff90247a4c5c5d9824f56f8c1> & __ptr64,<lambda_4606be27f17b5e5579e09050fab91818> >+0x2b  
ucrtbase!fwrite+0x67    

detail of ucrtbase as follow
0:020> lmvm ucrtbase
Browse full module list
start end module name
00007ffab3c80000 00007ffab3d7a000 ucrtbase (pdb symbols) c:\symbols\ucrtbase.pdb\9FB5798C91EBCA528CADC890FF6E04FF1\ucrtbase.pdb
Loaded symbol image file: ucrtbase.dll
Image path: C:\Windows\System32\ucrtbase.dll
Image name: ucrtbase.dll
Browse all global symbols functions data
Image was built with /Brepro flag.
Timestamp: 48AC8393 (This is a reproducible build file hash, not a timestamp)
CheckSum: 0010252D
ImageSize: 000FA000
File version: 6.2.17763.1490
Product version: 10.0.17763.1490
File flags: 0 (Mask 3F)
File OS: 40004 NT Win32
File type: 2.0 Dll
File date: 00000000.00000000
Translations: 0409.04b0
Information from resource tables:
CompanyName: Microsoft Corporation
ProductName: Microsoft® Windows® Operating System
InternalName: ucrtbase.dll
OriginalFilename: ucrtbase.dll
ProductVersion: 10.0.17763.1490
FileVersion: 10.0.17763.1490 (WinBuild.160101.0800)
FileDescription: Microsoft® C Runtime Library
LegalCopyright: © Microsoft Corporation. All rights reserved.

Developer technologies | C++
{count} votes

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.