I'm trying to implement OpenCV into my application but every time I call a function there is a memory leak. I guess it has something to do with how I have used the library with Visual Studio but I tested it with a blank project and it seemed to work fine with the same settings.
The code I'm trying to implement into:
int _tmain(int argc, TCHAR* argv[], TCHAR* envp[])
{
int nRetCode = 0;
// initialize Microsoft Foundation Classes, and print an error if failure
if (!AfxWinInit(::GetModuleHandle(NULL), NULL, ::GetCommandLine(), 0))
{
_tprintf(_T("Fatal Error: MFC initialization failed\n"));
nRetCode = 1;
}
else
{
// Application starts here...
// Time the application's execution time.
TIMER start;
// CODE TO GO HERE!
TIMER end;
TIMER elapsed;
elapsed = end - start;
__int64 ticks_per_second = start.get_frequency();
// Display the resulting time...
double elapsed_seconds = (double)elapsed.get_time() / (double)ticks_per_second;
cout << "Elapsed time (seconds): " << elapsed_seconds;
cout << endl;
cout << "Press a key to continue" << endl;
char c;
cin >> c;
}
return nRetCode;
}
If I implement something as simple as:
cv::Mat aVar;
in the space where I have put "CODE TO GO HERE!" Visual Studio says there is a memory leak once the program has terminated. Any ideas what the problem could be?
Like I said in your last post, the details are important. The non-MFC dll loads before MFC dll and if there is any data not freed before MFC exits, MFC falsely reports this as a memory leak. This is a known issue which is a problem when using opencv with mfc. The solution is to:
Static link MFC library (most common way)
Try the workaround to force mfc dll to be loaded first in the link above
Delay loading dlls as seen in this question.
I've noticed in the debug version that the combination of MFC and OpenCV can also result in strange behavior when you additionally use fopen and fread. fread might return error 9 (The storage control block address is invalid).
Again, delayed loading the OpenCV dlls might solve the problem.
Related
I'm attempting to debug some very opaque issues with DLLs in Unreal on a CI machine (see Unreal: Diagnosing why Windows cannot load a DLL for more information). glu32.dll seems to be the DLL at which the Unreal process falls over, and as Windows Server doesn't contain all the graphics-related DLLs that normal Windows 10 does, I was recommended to upload certain DLLs from my machine/Microsoft redistributables in order to make sure the Unreal build process could run.
For sanity purposes, I've written a small utility program to test whether glu32.dll on my machine can be dynamically loaded and can have its functions called correctly. I'm planning to run this executable on the troublesome CI machine soon to see what happens.
The code for the program is below:
#include <windows.h>
#include <iostream>
#include <GL/gl.h>
extern "C"
{
typedef const GLubyte* (__stdcall *ErrorStringFunc)(GLenum error);
}
int main(int argc, char** argv)
{
if (argc < 2)
{
std::cerr << "Usage: GLU32Loader.exe <path to glu32.dll>" << std::endl;
return 1;
}
const char* path = argv[1];
std::cout << "Attempting to load: " << path << std::endl;
HMODULE dllHandle = LoadLibraryA(path);
if (!dllHandle)
{
std::cerr << "Could not load " << path << std::endl;
return 1;
}
std::cout << "Successfully loaded DLL: 0x" << dllHandle << std::endl;
const char* funcName = "gluErrorString";
std::cout << "Looking up function: " << funcName << std::endl;
ErrorStringFunc func = reinterpret_cast<ErrorStringFunc>(GetProcAddress(dllHandle, funcName));
if (func)
{
std::cout << "Successfully loaded function: 0x" << func << std::endl;
const GLubyte* str = (*func)(100902);
std::cout << "Error string for value 100902: \"" << str << "\" (0x" << static_cast<const void*>(str) << ")" << std::endl;
}
else
{
std::cerr << "Failed to load function " << funcName << std::endl;
}
FreeLibrary(dllHandle);
return 0;
}
When I run the executable and point it to glu32.dll in the System32 folder, I get expected output:
> GLU32Loader.exe "C:\Windows\System32\glu32.dll"
Attempting to load: C:\Windows\System32\glu32.dll
Successfully loaded DLL: 0x00007FFC7A350000
Looking up function: gluErrorString
Successfully loaded function: 0x00007FFC7A35C650
Error string for value 100902: "out of memory" (0x000001E5757F51D0)
However, if I copy the DLL to my desktop and run the program again, although the DLL and function appear to be loaded, the string returned from the function is empty:
> GLU32Loader.exe "C:\Users\Jonathan\Desktop\glu32.dll"
Attempting to load: C:\Users\Jonathan\Desktop\glu32.dll
Successfully loaded DLL: 0x00007FFC8DDB0000
Looking up function: gluErrorString
Successfully loaded function: 0x00007FFC8DDBC650
Error string for value 100902: "" (0x0000025C5236E520)
Why would this be? It's exactly the same DLL, just in a different folder, and I would have thought that any other dependent DLLs that it references should still be available because they're all in System32. Is there some mystical property of Windows DLLs that I'm not familiar with that might cause this to happen?
This is an example of why one shall not mess around with system DLLs.
The DLL in question, like many Microsoft DLLs, uses MUI (Multilingual User Interface).
If you look at its resources, it has no resources except a MUI type resource, pointing to a folder containing the corresponding .mui file, which contains its actual (internationalized) resources.
So, if you still want to copy it, at least also copy the corresponding .mui file:
System32\glu32.dll → <my_files>\glu32.dll
System32\en-US\glu32.dll.mui → <my_files>\en-US\glu32.dll.mui
The en-US part may be different on your system depending on the default locale.
EDIT: I saw only now from your log that you didn't rename the file. Then I'm not sure what it can be. I'll leave this explanation up anyway because it would also be what happens if one were to rename that file, so maybe it is helpful to someone else...
It seems to me as if you renamed the DLL file (not just loaded it from another location but with another filename as well).
glu32.dll doesn't like to be renamed, because in some places code like GetModuleHandle("glu32.dll") is used instead of saving the hInstance received in DllMain into a global variable and using that handle (which is what should have been done, but unfortunately it isn't what Microsoft did). If you rename the DLL, this call will return NULL. Now unfortunately there also isn't much error handling going on in glu32 in that case.
The error strings are stored in global arrays of some sort, but they are lazy-loaded there from string table resources. The first time you call gluErrorString, the error strings are loaded using LoadString which takes the hInstance of the DLL. With the renamed DLL, this will be the bogus NULL handle, and calling LoadString(NULL, ...) will return 0, indicating an error. Normally the number returned is the length of the string. glu32 doesn't handle the zero case in any special way and just copies the zero characters to the array and happily returns an empty string to you at the end.
I want to change or read the pointer's value which is in other program.But i need to know pointer's address.Can i get the address without Cheat Engine and how can i do that ? In the youtube/google/facebook they are using Cheat Engine to know the address.
#include <iostream>
#include <windows.h>
int main() {
DWORD pointer = 0x006DFEF8; // I learned this address from Cheat Engine.
DWORD pid;
int deger;
char program_isim[100];
std::cin >> program_isim;
HWND program = FindWindow(0, program_isim);
if (program == 0) {
std::cout << program_isim << ",bulunamadi." << std::endl;
}
else {
GetWindowThreadProcessId(program, &pid);
HANDLE hand = OpenProcess(PROCESS_ALL_ACCESS, 0, pid);
while (1) {
ReadProcessMemory(hand, (void*)pointer, °er, sizeof(deger), 0);
std::cout << deger << std::endl;
}
}
return 0;
}
Cheat Engine is a disassembler and debugger. You can find pointers using both of these features, but everything is easiest when using a debugger at runtime. It allows you to set "break on read" and "break on write" breakpoints. The "find what accesses" function of Cheat Engine is just using read breakpoints and logging the addresses where the breakpoint is hit.
Cheat Engine will always be the best way to find pointers. Can you find a pointer via static analysis? Yes you can but it will be more difficult.
You can replicate Cheat Engine's behavior by writing your own program which registers itself as a debugger with the Windows API and set breakpoints on the target process.
But the reason you can't use Cheat Engine is because the game has anticheat that detects your debugger, it will also detect your debugger you write so this is not the solution.
The solution is to bypass the anticheat and then just use Cheat Engine as normal.
I'm creating a simple HACK for educational purpose only. A simple Triggerbot that reads from memory the value of player aiming to enemy YES = 1 or NO = 0. I have made some other similar HACKS however I never found this problem .. in Rainbow Six Siege I have the memory address both static or dynamic however cheat engine read it well but when I try to read it from my C++ Program it does't work. Not sure why if it had work with other games. I'm new to this and maybe I did something wrong.
#include "stdafx.h"
#include <iostream>
#include <windows.h>
#define F6Key 0x75
using namespace std ;
int value ;
int main()
{
cout << "Open Game .." << endl ;
system("Pause") ;
LPCWSTR gameone = L"Rainbow Six";
HWND hwnd = FindWindow(0, gameone);
if (gameone == 0)
{
cout << "Not Found." << endl ;
system("Pause") ;
}
else
{
cout << "Success finding game." << endl;
DWORD processid ;
GetWindowThreadProcessId(hwnd, &processid) ;
HANDLE process = OpenProcess(PROCESS_ALL_ACCESS, FALSE, processid) ;
cout << processid ;
if (!ReadProcessMemory(process, (void *)0x25421AD9D6C, (void *)&value, sizeof(value), NULL)) {
cout << "Unable to read memory proccess";
}
else {
cout << "\n Read: " << value;
}
system("Pause");
}
return 0 ;
}
Here is the code simple Find the Window by name, gets its PID fine no problem. OpenProcess then when I call the method ReadProcessMemory with the process, address pointer value by parameter is unable to read it print the if condition and never the else of value read.
If I remove the function from the If condition just for testing if at least points to something it gives some random values... is weird that I'm unable to read memory It always work ::(
Can someone help me out? It is some king of security software or something?
First of all, you have to check OpenProcess return value. If your process does not have sufficient rights, it will return NULL and any attempts to use this handle will fail. Use GetLastError function to determine error reason.
Most likely it will be ERROR_ACCESS_DENIED.
Secondary, to successfully access external process memory space, you should open its handle with PROCESS_VM_READ right or enable seDebugPrivilege for you process token. Example how to do that you could see in the MSDN.
And lastly. If memory address (0x25421AD9D6C in your case) is invalid, ReadProcessMemory will fail. In that case value variable would not be initialized and any attempts to use it is an undefined behavior.
Also, if you managed to get process handle, it should be closed using CloseHandle function when you finish using it.
Upd: If ReadProcessMemory returns FALSE and GetLastError - ERROR_PARTIAL_COPY that means that a page fault has occured, you are trying to read from a buffer and at least part of it is not assigned to the physical memory. If you know your value offset, get module load address using PSAPI GetModuleInformation function and add offset to the lpBaseOfDll field of the MODULEINFO structure.
I'm working on a big C++ project which I haven't created, but the following short code fully represents a problem which I'm faced with:
#include <string>
#include <iostream>
int main(int argc, char **argv){
using namespace std;
try{
string str;
str = "r";
double d = stod(str);
cout << "'stod' worked! d = " << d << endl;
}
catch (invalid_argument){
cout << "I'm in 'catch'\n";
}
cout << "I'm after 'try-catch'\n";
cin.get();
cin.get();
return 0;
}
If I launch the code without debugger, everything works fine and as expected it gets into the catch-scope and then main() proceeds.
If I use the debugger, Visual Studio under 32-bit configuration restarts immediately or under 64-bit configuration I get a message: "The debugger's worker process (msvsmon.exe) unexpectedly exited. Debugging will be aborted."
I'm using VS2013 Ultimate on Windows 8.1 Professional.
Due to this post:
msvsmon.exe crashed when debugging
I have already installed Update 4. I have no breakpoints. In DEBUG->EXCEPTIONS the reset was done.
I also do not understand, what msvsmon.exe is. The Google-search combines it with remote debugger which confuses me a little bit, because I'm using the local debugger, at least I press each time the 'Local Windows Debugger' button.
Could anybody help me out?
The program I am writing is a simple console application that gets params, computes, and then returns data.
I am asking this because I am trying to implement a smart "press enter to exit" message that would run only if a console program is called by clicking on its icon in explorer. Without it, the result is that program only flashes for a split of second, but if a program is run from a context of already opened console then the same thing becomes an annoyance. Similar thing arises when program is run inside bat or cmd file, then pausing at the end is also unwelcome since bat files have 'pause' command that is supposed to do it.
So, we have 2 modes:
program says "press enter to exit" when is started by:
direct clicking in explorer
clicking on a shortcut
Simply exit when:
its name is typed in console
it is run from a bat/cmd file
it is run from another console application
Using Windows APIs:
You can use the GetConsoleProcessList API function (available on Windows XP/2003 and higher only). It returns a list of processes that are attached to the current console. When your program is launched in the "no console" mode, your program is the only process attached to the current console. When your program is launched from another process which already has a console, there will be more than one process attached to the current console.
In this case, we don't care about the list of process IDs returned by the function, we only care about the count that is returned.
Example program (I used Visual C++ with a Console Application template):
#include "stdafx.h"
#include <iostream>
#include <Windows.h>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
DWORD procIDs[2];
DWORD maxCount = 2;
DWORD result = GetConsoleProcessList((LPDWORD)procIDs, maxCount);
cout << "Number of processes listed: " << result << endl;
if (result == 1)
{
system("pause");
}
return 0;
}
We only need to list up to 2 processes, because we only care whether there is 1 or more than 1.
Using Windows APIs present in Windows 2000:
GetConsoleWindow returns the window handle of the console associated with the current process (if any). GetWindowThreadProcessId can tell you which process created a window. And finally, GetCurrentProcessId tells you the id of current process. You can make some useful deductions based on this information:
#include "stdafx.h"
#include <iostream>
#include <Windows.h>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
HWND consoleWindow = GetConsoleWindow();
if (consoleWindow != NULL)
{
DWORD windowCreatorProcessId;
GetWindowThreadProcessId(consoleWindow, &windowCreatorProcessId);
if (windowCreatorProcessId == GetCurrentProcessId())
{
cout << "Console window was created by this process." << endl;
system("pause");
}
else
cout << "Console window was not created by this process." << endl;
}
else
cout << "No console window is associated with this process." << endl;
return 0;
}
This technique seems slightly less precise than the first one, but I think in practice it should perform equally well.
The simplest solution I can think of is require the first parameter to be a flag whether or not the program should pause at the end. If the parameter is not there, i.e. it was started via explorer and the user did not have the ability to pass it in, then it should pause.
//Pseudo-code!!
int main(int argc, char** argv) {
//...
if(argv[1] == SHOULD_PAUSE) system("pause");
return 0;
}
There's a simple way to do this, and of course a more complicated way. The more complicated way may be more fun in the end, but probably more trouble than it's worth.
For the simple way, add a command line argument to the program, --pause-on-exit or something similar. Pass the extra arg whan calling it from a batch-file or the launcher icon. You could of course rather check for an environment variable for a similar effect.
For a more complicated (and automatic) way, you could probably try to find out who is the parent process of your application. You may have to go further up the chain than your immediate parent, and it may not work in all cases. I'd go for the command line argument.
Elaborating on my comment, rather than trying to tell how the program was executed (which I don't know is even possible, I'd assume there's no difference/distinction at all), I would implement a similar functionality in either one of two ways:
Add an extra argument to the program that will either make it "pause" at the end before terminating or not. ie. You could have something like -w to make it wait, or -W to make it not wait, and default with not waiting (or vice versa). You can add arguments through shortcuts.
Add a timer at the end of the program so that you wait for a few seconds, long enough for the user to read the input, so that the program doesn't wait infinitely when used in a batch.
Visual Studio introduces a wrinkle to #tcovo's otherwise valid answer when you are debugging. In this situation, it creates a second process and attaches it to the same console as the process you're running in:
So, it's necessary to detect the debugger using the Windows API function IsDebuggerPresent in order to get a definitive answer:
#include <iostream>
#include <Windows.h>
#include "debugapi.h"
int main()
{
DWORD pl[2];
auto np = GetConsoleProcessList(pl, 2);
std::cout << np << " processes\n";
bool shared;
if (IsDebuggerPresent())
shared = np > 2;
else
shared = np > 1;
std::cout << "Shared: ";
std::boolalpha(std::cout);
std::cout << shared << "\n";
std::cin.ignore(1);
return 0;
}
This only matters if you're using the local debugger; when run in a remote debugger there is still only one process attached.