C++ Visual Studio Release build unused code crash - c++

I have a question which is quite general, but I hope someone will be able to at least point me in the right direction.
I created my project a I was building it only in Debug mode with /MDd flag.
But it started to have perfomance issues, so I wanted to try it in Release mode to see, how it goes.
Problem is, that when I use /MD or /MT flag and Release mode my application instantly crashes.
So I tried to find out why. It works fine in Debug. I've tried some code changes, but nothing helped. So I decided to make my app just start and comment out rest of my code. But it was still crashing. Even when my code was unused. It didn't crash only, when I completly removed those unused parts of code.
I think it's something with variable inicialization/declaration, but I'm not quite sure what I should look for.
Could someone suggest me what can cause application to crash even if it's just Declaration/Inicialization and is not even used in RunTime?
I hope you can somehow understand what is my problem.
Thanks for any suggestions!
EDIT: Code which crashes, when unused code is in project, but does not crash when i remove unused code.
#include "core/oxygine.h"
#include "Stage.h"
#include "DebugActor.h"
//#include "Galatex.h"
using namespace oxygine;
//called each frame
int mainloop()
{
//galatex_update();
//update our stage
//update all actors. Actor::update would be called also for all children
getStage()->update();
if (core::beginRendering())
{
Color clearColor(32, 32, 32, 255);
Rect viewport(Point(0, 0), core::getDisplaySize());
//render all actors. Actor::render would be called also for all children
getStage()->render(clearColor, viewport);
core::swapDisplayBuffers();
}
//update internal components
//all input events would be passed to Stage::instance.handleEvent
//if done is true then User requests quit from app.
bool done = core::update();
return done ? 1 : 0;
}
//it is application entry point
void run()
{
ObjectBase::__startTracingLeaks();
//initialize Oxygine's internal stuff
core::init_desc desc;
#if OXYGINE_SDL || OXYGINE_EMSCRIPTEN
//we could setup initial window size on SDL builds
desc.w = 1800;
desc.h = 1000;
//marmalade settings could be changed from emulator's menu
#endif
//galatex_preinit();
core::init(&desc);
//create Stage. Stage is a root node
Stage::instance = new Stage(true);
Point size = core::getDisplaySize();
getStage()->setSize(size);
//DebugActor is a helper actor node. It shows FPS, memory usage and other useful stuff
DebugActor::show();
//initialize this example stuff. see example.cpp
//galatex_init();
#ifdef EMSCRIPTEN
/*
if you build for Emscripten mainloop would be called automatically outside.
see emscripten_set_main_loop below
*/
return;
#endif
//here is main game loop
while (1)
{
int done = mainloop();
if (done)
break;
}
//user wants to leave application...
//lets dump all created objects into log
//all created and not freed resources would be displayed
ObjectBase::dumpCreatedObjects();
//lets cleanup everything right now and call ObjectBase::dumpObjects() again
//we need to free all allocated resources and delete all created actors
//all actors/sprites are smart pointer objects and actually you don't need it remove them by hands
//but now we want delete it by hands
//check example.cpp
//galatex_destroy();
//renderer.cleanup();
/**releases all internal components and Stage*/
core::release();
//dump list should be empty now
//we deleted everything and could be sure that there aren't any memory leaks
ObjectBase::dumpCreatedObjects();
ObjectBase::__stopTracingLeaks();
//end
}
#ifdef __S3E__
int main(int argc, char* argv[])
{
run();
return 0;
}
#endif
#ifdef OXYGINE_SDL
#include "SDL_main.h"
extern "C"
{
int main(int argc, char* argv[])
{
run();
return 0;
}
};
#endif
#ifdef EMSCRIPTEN
#include <emscripten.h>
void one() { mainloop(); }
int main(int argc, char* argv[])
{
run();
emscripten_set_main_loop(one, 0, 0);
return 0;
}
#endif

So I'll write it here for possibly other newbies like me which would find themselves in similar sutiation.
My problem was in Initialization of static and other variables which were "outside of function". For example:
MyObject object = new MyObject(); //This was the reason, why it was crashing, just had to move
// initialization of such variables to function which was called with object creation.
void MyClass::myFunction(){
object->doSomething();
}
So when program started inicialization of those variables caused crash of program.
Note: It seems like it was problem with objects, cause variables like Integers or such were just fine.
Well, I'm not totally sure why this is allowed in Debug mode, but crashes Release mode right after start, maybe someone could answer under this comment and explain this behavior, I'm just begginer and I'm doing lot of bad stuff, but I'm trying and that's good, right? :D
I hope i didn't waste too much of your time guys and maybe this post will be useful to someone in future.

Related

How i can implement a BackgroundWorker in C++ STL

Hello i'm newbie in C++ specially on STL,
I need to create a function with an infinite loop to calculate and process big data (such as Genetic Algorithm), but i also need keep Ui responsive and update it within (after each round) that infinite loop and start/stop operation manually.
something like this:
bool working = false;
void do_process()
{
while(working)
{
// do some stuff
}
}
void btnStart()
{
working = true;
do_process();
}
void btnEnd()
{
working = false;
}
would you please guide me to a proper solution without any 3rdparty lib, thanks.
and apologies for terrible English.
The code below should get you started. But be careful, implementing a multi-threading application is generally a hard problem also for experienced users. Lot of knowledge is required about memory access synchronization and deadlock analysis. Consider the example below is really essential. For instance, in btnStart and btnStop you should check if a thread is already running. Checking the global bool working may require synchronization. Similarly, checking for null pointer may require synchronization. Bottom line, it is way more complicate than it may seem.
#include <iostream>
#include <utility>
#include <thread>
#include <chrono>
#include <memory>
bool working = false;
std::unique_ptr<std::thread> t;
void do_process()
{
while(working)
{
std::cout << "Hi. I am a secondary thread and I am running.\n";
std::this_thread::sleep_for(std::chrono::milliseconds(100));
}
}
void btnStart()
{
working = true;
t.reset(new std::thread(do_process)); // start the thread
}
void btnEnd()
{
working = false; // inform the thread of termination
t->join(); // wait for thread termination
t.reset(NULL);
}
int main()
{
std::cout << "Hi, I am the main thread.\n";
std::cout << "I'll now launch another thread and sleep for a while\n";
btnStart();
std::this_thread::sleep_for(std::chrono::milliseconds(2000));
btnEnd();
std::cout << "What happened while I was slepping?\n";
return 0;
}
I am fairly new also to c++ but i have something that might help.
when i want to run something like an update to my code or to run something external without cramming my original project with code, i like to use ShellExecute to run another c++ program or external program. To use ShellExecute you need #include<windows.h>
For example if i want to update my program, i use #include<fstream>, #include<windows.h>, and #include<string> to check for a value in a file called 'updatereq.txt' (i make it my self). And in my program i run ifstream to check in the file if there is a '1'. If the if statement detects '1' it does this:
void Update(string filename)
{
ShellExecute(NULL,"open",filename.c_str(),NULL,NULL,SW_SHOWNORMAL)
}
This will run with:
HWND set as NULL, Operation set as: "open", File set as string:filenameconstant, Parameters set as NULL, Directory set as NULL(will run in the Directory of originally launching, usually at the main file), and Mode set as SW_SHOWNORMAL which will run it infront of you normally. This is also SW_SHOWMINIMIZED and SW_SHOWMAXIMIZED
Hope this helps!
PS: Remember to mention the file / program name that you are going to run when calling this function

Why does the construction of a 'CImage' (GDI+) make the programm crash?

I wanted to try using the class CImage, which comes from GDI+, to load an image and draw it at some place in my Graphical User Interface.
However, the programm crashes as soon as I call CImage's constructor, it seems, displaying the error:
Unhandled exception at 0x7757D968 (ntdll.dll) in myProgramm.exe: 0xC0000005: Access violation writing location 0x00000014
If I choose to break the programm after the exception, I can see that the cursor, which indicate the current called function, is pointing some CImage's method :
CImage::CInitGDIPlus::IncreaseCImageCount()
That's a reason why I was supposing GDI+ initialization could be the cause of the problem. So I have written a sample to possibly identify the problem, trying whether to initialize GDI+ or not.
// main.cpp
// (Do not forget to link gdiplus.lib and activate "Use MFC in a shared DLL")
#include <afxwin.h>
#include <afxdockablepane.h> // CImage seems to be unknown without this include. (My actual program uses it anyway.)
#include <Gdiplus.h>
void testWithoutGdipInititalization()
{
CImage image ; // The programm seems to crash here, at the construction of the image...
}; // ...And not here, at the destruction of the image
void testWithGdipInititalization()
{
// Initialize GDI+.
Gdiplus::GdiplusStartupInput gdipStartupInput;
ULONG_PTR gdipToken ;
Gdiplus::GdiplusStartup(&gdipToken, &gdipStartupInput, NULL);
{
CImage image ; // The programm seems to crash here, at the construction of the image...
} // ...And not here, at the destruction of the image
// Close Gdiplus
Gdiplus::GdiplusShutdown(gdipToken);
};
int main(int argc, char *argv[])
{
bool withInitialization = true ;
if(withInitialization)
testWithGdipInititalization();
else
testWithoutGdipInititalization();
return EXIT_SUCCESS;
}
...And both fail the same way.
Does someboy know what I'm doing wrong ?

C++ - Restarting a game by calling the main() function

I'm building a small game.
One of the input options is to restart the game. The only way I could think of doing this was to call the main function from within the main function
int main(int argc, char argv[]) {
...
if (input == "restart") {
main(argc, argv);
}
Is this bad form? Will it even work?
No, the C++ standard disallows calling main manually.
To cite the standard (C++11: 3.6.1 Main Function)
The function main shall not be used within a program. The linkage
(3.5) of main is implementation-defined.
A program that defines main as deleted or that declares main to be inline, static, or constexpr is ill-
formed. The name main is not otherwise reserved.
You can't call main() recursively. That's actually undefined behavior.
Use a loop instead:
int main() {
bool restart = false;
do {
// Do stuff ...
// Set restart according some condition inside of the loop
if(condition == true) {
restart = true;
} // (or simplyfied restart = condtion;)
} while(restart);
}
Do not do this. From http://en.cppreference.com/w/cpp/language/main_function
The main function has several special properties:
1) It cannot be used anywhere in the program
a) in particular, it cannot be called recursively
Since recursively calling main is impossible in C++ and would not really solve the problem, here's my 2 cents on how to deal with the problem:
Basically, any large program is a loop that might look like this:
int main()
{
bool quit = false;
//Initialise and aquire resources...
while (!quit)
{
//Run game and set quit if user wants to quit...
}
//free resources, should be automatic when RAII is adhered.
}
Your game should already look something like this, since any program that is not a loop will immidiately quit and won't be much of a game. Just change the structure to this:
int main()
{
bool quit = false;
bool restart = false;
while (!quit)
{
Restart = false;
//Initialise and aquire resources...
while (!quit && !restart)
{
//Run game and update quit and restart according to user input.
}
//free resources, should be automatic when RAII is adhered.
}
}
you can use GOTO but this is not a good way of programming in general. As the guys mentioned to use booleans or loops to check the current state or any other way instead of goto because it causes sometimes problems in the compiler. However it is still available in C and not C++ (AFAIK)
If in addition to reloading internal resources, you also need to reload external things like a libraries that the game links to you can do this by re-launching the game in a thread, detaching the thread and then shutting down.
I use this in a game I've made where I have automatic updates, to start the new updated executable and libraries.
int main() {
//initialize the game
bool restart=false, quit=false;
while (!quit) {
//Main loop of the game
}
if (restart) {
#ifdef _WIN32
std::thread relaunch([](){ system("start SpeedBlocks.exe"); });
#elif __APPLE__
std::thread relaunch([](){
std::string cmd = "open " + resourcePath() + "../../../SpeedBlocks.app";
system(cmd.c_str());
});
#else
std::thread relaunch([](){ system("./SpeedBlocks"); });
#endif
relaunch.detach();
}
return 0;
}
A bit of a hack, but it gets the job done. The #ifdefs just make it use the correct launch cmd for Windows/Max/Linux.

C++ refreshing thread

I have this project I'm working on where I have a label that displays the robot coordinates. However to do (and because of a specific case) I need to make a function run like every 1 second to give me those values.
It would be something like this every second:
label1->Text = read_position(axis1);
But I have no idea how to make it.. Can please someone help? Thanks !
EDIT: Using Visual Studio 2015
If you're using some GUI framework, i'd advised you not to use multithreading for such a simple thing. For instance, in win32 you can use SetTimer function.
You have added the 'multithreading' tag, so I suppose you are free to use multiple threads. So, the way to do this is by launching a new thread which will be doing the following:
while( ! instructed_to_quit() )
{
give_him_those_values();
sleep_for_a_second();
}
The specifics of precisely how to achieve each of these steps is largely dependent on what kind of system you are running on, which you have been rather secretive about, so if you tell us more about that, we might be able to help more.
Since you are using Visual Studio 2015, you can use standard threads and atomic variables of C++11. There are some different possible solutions, the following is one of them.
static MyRobotForm myRobot(void);
static std::thread reader;
static std::atomic<double*> coordinates(nullptr);
static std::atomic<bool> shutdown(false);
static void position_reader() {
// loop until app is alive
while(!shutdown) {
// fetch the coordinates array
double *temp = read_all_axis(myRobot.Cp, decision);
// atomically replace the old unused value or nullptr
temp = coordinates.exchange(temp);
// it is safe to delete nullptr
delete temp;
// sleep for the proper time
std::this_thread::sleep_for(1s);
}
// finicky but correct
delete coordinates.load();
}
int main(int argc, char **argv) {
// start the reading thread
reader = std::thread(position_reader);
// where depends on gui toolkit ???
// atomically seize the current value
double *temp = coordinates.exchange(nullptr);
if(temp != nullptr) {
label1->Text = std::string(/*decide how to display temp*/);
delete temp;
}
// on application exit
shutdown = true;
reader.join();
return 0;
}
I have not tested it but it should work. What GUI toolkit are you using? *)

C++ destructor called early

I have a class that manages a SDL_Surface for me, and I want to make it so that I don't have to worry about freeing the surface. I have this code so far:
//In Entity.h
class Entity
{
public:
int x, y, width, height;
Entity(std::string);
~Entity();
void render();
private:
SDL_Surface* texture;
};
//In Entity.cpp
Entity::~Entity()
{
printf("Destroying an Entity");
SDL_FreeSurface(texture);
}
//In main.cpp
Entity puppy("puppy.bmp");
void render() {
clearScreen();
puppy.render();
}
int main (int argc, char **argv) {
printf("started");
init();
bool done = false;
while(!done)
{
...
// Draw the screen
printf("About to render");
render();
SDL_Flip(screen);
}
SDL_Quit();
return 0;
}
When I run it, I get Program received signal EXC_BAD_ACCESS, Could not access memory.
Reason: KERN_INVALID_ADDRESS at address: 0x0000000000000260
0x000000010002fd9b in SDL_DisplayFormat () Am I correct in assuming that the destructor is getting called early and it's trying to render a NULL texture? The code works fine if I don't have the destructor and just waste memory. I've also tried it with puppy being a local variable and passing it to render, but that doesn't help.
EDIT: The code runs for only a second, then crashes. It doesn't wait to exit the loop. Also, stepping through the program with gdb reveals the puppy to be drawn at least once for some reason. I've uploaded the full source here: http://dl.getdropbox.com/u/2223161/sdlgame.zip
This is a global variable:
Entity puppy("puppy.bmp");
it gets destroyed after your main() ends, so your SDL_FreeSurface gets called after SDL_Quit(). Is it valid? Check with documentation.
You're looking at the wrong end of the problem. Your code ran for me after I moved the initialization of puppy into main.
By placing puppy as a global object, its constructor runs prior to SDL_Init. The constructor calls load_image, which calls SDL_DisplayFormat. The documentation warns:
You have to call SDL_Init before using the SDL_DisplayFormat function. If you don't, your program will crash with an access violation.
http://sdl.beuc.net/sdl.wiki/SDL_DisplayFormat
Of course, you should also ensure the destructor is called prior to SDL_Quit(), as is proper, though that's not what's causing your access violation at the moment.