c++ static local variable initialization in dll cause _CrtIsValidHeapPointer exception - c++

I have an exception is a dll i'm using when initializing a static local variable to a class instance.
The exception occurs when returning from the class constructor.
The exception I get in release is:
ConsoleApplication1.exe: 0xC0000005: Access violation reading location 0x00000000BA3529A2.
and in debug I get a debug assertion:
Debug Assertion Failed!
Program: E:\Sandbox\ConsoleApplication1\x64\Debug\ConsoleApplication1.exe
File: f:\dd\vctools\crt\crtw32\misc\dbgheap.c
Line: 1516
Expression: _CrtIsValidHeapPointer(pUserData)
This is the function that fail (Part of the CImg library which is excellent!):
static const CImg<Tuchar>& jet_LUT256() {
static CImg<Tuchar> colormap; // <--- static local variable decleration
// exception here. after returnning from the CImg constructor :-(
cimg::mutex(8);
if (!colormap) {
colormap.assign(1,4,1,3,0);
colormap[2] = colormap[3] = colormap[5] = colormap[6] = colormap[8] = colormap[9] = 255;
colormap.resize(1,256,1,3,3);
}
cimg::mutex(8,0);
return colormap;
}
When the project was running as an exe everything worked fine.
Problem started when I made it a dll, and used it in another exe.

Solved.
Found out that the problem was that I used the /NOENTRY property (big NONO!)
(because when I converted it from exe to dll I had a link error with unresolved function mainCRTStartup)
removed the /NOENTRY from Properties->Linker->Advanced and error is gone.

Related

Loading dynamcally a DLL inside another DLL

I'm trying to convert the functionality of our old code to a DLL.
One of the function wants to export from our old code use a dynamically linked DLL (that I'm gonna call other)
std::wstring otherDLL = L"C:\\PATH\\TO\\OTHER\\DLL"
if (!(libOther = LoadLibraryW(otherDLL.c_str()))){
return;
}
In our old code, this portion of code works just fine.
So I added in my new DLL the following code:
extern "C++" std::wstring test_load(void){
std::wstring otherDLL = L"C:\\PATH\\TO\\OTHER\\DLL"
if (!(libOther = LoadLibraryW(otherDLL.c_str()))){
return L"Not Loaded";
}
return L"Loaded";
}
(this function is not launched during DLLMain). If I try to launch test_load from my DLL in another exe
#include "MyNewDLL.h"
int main()
{
std::wcout << test_load();
}
I get following error
Unhandled exception at 0x7BDE20f3 (ucrtbased.dll) in Test.exe: 0xC00000005: Access violation reading location 0x00000000
What's strange is that if I try to load the OtherDLL from the main that is not inside MyNewDLL, there is no error and I can use it just fine.
Any Idea where my problem could come from ?

C++ - Having problems defining a variable inside main() function

I am trying to define a variable from an external library in C++, Visual Studio 2010. It only works when I put it outside of the main function.
This code crashes:
#include "StdAfx.h"
#include <ogdf\basic\Graph.h>
#include <ogdf\basic\graph_generators.h>
int main()
{
ogdf::Graph g;
ogdf::randomSimpleGraph(g, 10, 20);
return 0;
}
It gives me an unhandheld exception: Access violation.
However, if it is outside main function, it works without any problem:
#include "StdAfx.h"
#include <ogdf\basic\Graph.h>
#include <ogdf\basic\graph_generators.h>
ogdf::Graph g;
int main()
{
ogdf::randomSimpleGraph(g, 10, 20);
return 0;
}
Do you have any how do I fix that? I assume, that it is caused by some kind of linking problem.
EDIT: It looks like the problem is not the initialization of the variable. It throws an exception, when the application exits.
int main()
{
ogdf::Graph g; // No problem
ogdf::randomSimpleGraph(g, 10, 20); // No problem
int i; // No problem
std::cin>>i; // No problem
return 0; // Throws an exception after read i;
}
Call stack:
The output is:
First-chance exception at 0x0126788f in graphs.exe: 0xC0000005: Access violation writing location 0x00000000.
Unhandled exception at 0x0126788f in graphs.exe: 0xC0000005: Access violation writing location 0x00000000.
Works on my machineā„¢.
Esoteric errors like that are often a result of binary incompability. Basically, because of different compiler/preprocessor options, effective headers that your code and the library "see" are different.
For instance, if you have a library with following header code:
class Foo
{
#ifdef FOO_DEBUG
int debug_variable;
#endif
int variable;
};
Library function:
void bar(Foo& foo)
{
std::cout << foo.variable;
}
And client code:
Foo foo;
foo.variable = 666;
bar(foo);
If FOO_DEBUG is not in sync amongst client and the library, this will possibly crash and burn -- variable will have different expected offset.
In your case, I suspect one of the following may be true:
You have built the ogdf with different compiler than your code
If not, you ogdf and your code have different build configurations (Release vs Debug)
Both are debug, but you have defined OGDF_DEBUG (as recommended here)
You have different "Struct Member Alignment" setting

First-chance exception (ntdll.dll)

Any ideas why I am getting this error?
This is the full error:
First-chance exception at 0x77202282 (ntdll.dll) in Test.exe 0xC0000005: Access violation writing location 0x0000004
Unhandle exception at 0x77202282 (ntdll.dll) in Test.exe 0xC0000005: Access violation writing location 0x0000004
Debugging breaks at the line Grid::Grid().
Root.hpp contains a private member static Grid grid;.
Root.cpp initializes this Grid Root::Grid;
I do have SFML linked statically, which has caused me a bit of trouble.
This is a small example which exhibits this error:
#include <fstream>
#include <sstream>
#include <Windows.h>
#include "Root.hpp"
Grid Root::grid;
int main (uchar argc, char **argv) {
Root root;
Root::Prepare(root);
return Root::GetStatus();
}
The constructor as follows:
Grid::Grid() {
Width = 100;
Height = 100;
}
The call stack:
ntdll.dll!772022b2() Unknown
[Frames below may be incorrect and/or missing, no symbols loaded for ntdll.dll]
Test.exe!sf::priv::MutexImpl::lock(void) Unknown
Test.exe!sf::Mutex::lock(void) Unknown
Test.exe!sf::Lock::Lock(class sf::Mutex &) Unknown
Test.exe!sf::GlResource::GlResource(void) Unknown
Test.exe!sf::Texture::Texture(void) Unknown
> Test.exe!Grid::Grid() Line 5 C++
Test.exe!`dynamic initializer for 'Root::grid''() Line 11 C++
msvcr110d.dll!_initterm(void (void) * * pfbegin, void (void) * * pfend) Line 894 C
Test.exe!__tmainCRTStartup() Line 460 C
Test.exe!mainCRTStartup() Line 377 C
kernel32.dll!767533aa() Unknown
ntdll.dll!77219ef2() Unknown
ntdll.dll!77219ec5() Unknown
Even without having your full source code, the exception you're getting, and the stack you show, look suspiciously similar to another solved Stack Overflow posting:
"Unhandled exception at 0x777122D2 (ntdll.dll) in ArticxEngine.exe: 0xC0000005: Access violation writing location 0x00000004"
Your stack shows that Grid() is derived from SFML's Texture(), which is derived in turn from GlResource(). The problem is that your grid is a static variable which is getting constructed before GlResource()'s internal mutex is.
The solution is the same as the other Stack Overflow posting: make sure your Grid object is non-static and is constructed after your main() begins running.

Poco Mutex causes unhandled exception after close of the program

I get an unhandled exception if I close my program using Poco mutexes.
I use a global
Poco::Mutex mymutex ;
in my cpp file, because I have a static class for logging (I also tried to declare it as a static member, but I got the same error).
The relevant part of my code (it's a static function):
void Log::log(std::string message)
{
try
{
Poco::Mutex::ScopedLock lock(mymutex);
std::ofstream f("log.txt", std::ios_base::app) ;
f << message << std::endl ;
f.close() ;
}
catch (...)
{
}
}
This part of the code works great in my program (there are no lines on each other like before using mutexes), but after I close my program, I get the following error message:
Unhandled exception at 0x77c3a710 in myprogram.exe: 0xC0000005:
Access violation writing location 0x00000014.
I also tried to use mymutex.lock() and mymutex.unlock() before and after writing to the file, but I got the same error.
And I also tried this code:
while(!mymutex.tryLock())
Poco::Thread::sleep(30);
but it resulted an infinite loop, the program has not stopped after closing its window.
I use Visual Studio 2010 and Poco 1.4.

Need help correcting Access Violation with FFmpeg DLL

I'm trying to use the FFmpeg dll's using Visual Studio 2012 and I'm getting a run time access violation when I call avcodec_find_encoder. Here is the code:
// TestFFmpeg.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
extern "C" {
#include "libavcodec\avcodec.h"
#include "libavformat\avformat.h"
}
#define INBUF_SIZE 4096
int _tmain(int argc, _TCHAR* argv[])
{
AVCodec *codec;
const char *videoFilename = "C:\\Users\\Public\\Videos\\Sample Videos\\Wildlife.wmv";
av_register_all(); // This works; however, no parameters or return values.
codec = avcodec_find_encoder(CODEC_ID_WMV3); // Run time Access Violation HERE
if (!codec) {
fprintf(stderr, "Codec not found\n");
exit(1);
}
return 0;
}
Here is the error message:
Unhandled exception at 0x75C18B60 (msvcrt.dll) in TestFFmpeg.exe: 0xC0000005: Access violation reading location 0x00000049.
The stack trace is:
msvcrt.dll!_strcmp() Unknown
avcodec-54.dll!6a56caac() Unknown
[Frames below may be incorrect and/or missing, no symbols loaded for avcodec-54.dll]
> TestFFmpeg.exe!wmain(int argc, wchar_t * * argv) Line 23 C++
TestFFmpeg.exe!__tmainCRTStartup() Line 533 C
TestFFmpeg.exe!wmainCRTStartup() Line 377 C
kernel32.dll!#BaseThreadInitThunk#12() Unknown
ntdll.dll!___RtlUserThreadStart#8() Unknown
ntdll.dll!__RtlUserThreadStart#8() Unknown
I'm guessing there's a problem with returning the codec pointer, but I'm new to C++ and have no idea how to correct it. I tried the cdecl, stdcall, and fastcall calling conventions -- none corrected the issue. I'm using the latest 32-bit DLL from Zeranoe. Any suggestions?
EDIT:
I've called other functions in the DLL and they work. For example, avformat_open_input works properly. I can pass parameters and the function returns a successful return value (0) and populates the format context structure. av_find_stream_info works as well. I still can't figure out why avcodec_find_decoder creates an access violation.
Finally, fixed it. I did two steps and I'm not sure which one worked (heh):
Added the '.lib' files as linker input dependencies
I picked up the Sept 7 build and made sure I have all the same build-date for the dll's, libraries, and include files.
Everything appears to work fine now.