I have an issue writing into a stream, passed as a FILE* to a function which is contained in a DLL. Compiler: Visual C++, all versions 2005 to 2015. The precise errors vary; the VS 2015 version is given below. The problem is identical for Win32 and x64 targets.
Trying to boil down the problem, consider this function:
#include <stdio.h>
void TestPrintf(FILE *TestFile)
{
fprintf(TestFile, "Hello World");
}
Now, another function will be calling the above function in the following way:
#include <stdio.h>
void TestPrintf(FILE *TestFile);
void AnyFunction( void )
{
FILE *TestFile;
fopen_s( &TestFile, "PrintTest.txt", "wt");
TestPrintf(TestFile);
}
The first function is part of a DLL. Depending on the settings in Properties / C/C++ / Code Generation during compilation of both the DLL and the program containing the caller, I get the following error messages:
Caller compiled for Multithread Debug (static):
DLL compiled for either Multithread Debug (static) or Multithread Debug DLL:
Debug assertion failed
File: minkernel\crts\ucrt\src\appcrt\heap\debug_heap.cpp
Line: 980
Expression: __acrt_first_block == header
DLL compiled for Multithread (static):
Debug assertion failed in the same file as before, but now
Line: 892
Expression: is_block_type_valid(header->block_use)
DLL compiled for Multithread DLL:
Again another variant of the same. Now it is:
Line: 888
Expression: _CrtlsValidHeapPointer(block)
Caller compiled for Multithread Debug DLL:
DLL compiled for either Multithread (static) or Multithread Debug (static):
same messages as above
DLL compiled for Multithread DLL:
Yet another variant of the same. Now it is:
HEAP[FilePrintTest.exe]: Invalid address specified to RtlValidateHeap(
01060000, 0107B7A0 )
DLL compiled for Multithread Debug DLL:
This is error-free.
Caller compiled for Release (either Multithread or Multithread DLL):
all four versions of the DLL go error-free.
The difference between VS versions seems to be that VS 2015 first writes the output as intended and crashes afterwards, whereas VS 2005 crashes already while writing the output.
If the function TestPrintf is not in a DLL, but in a static library, there is no such problem (of course, there will be linker messages about library collisions, but the test program works nonetheless). However, unfortunately, I do need the writing function inside the DLL, and I must be able to call it from anywhere.
All of the above applies also to the case that the caller is in a console programme and the stream is stdout.
So my question is: Is there a stupid mistake on my side? If not, is there a way to work around this problem?
I would be grateful for suggestions!
Martin