当前位置: 动力学知识库 > 问答 > 编程问答 >

C++ Application behaves differently from code

问题描述:

I am writing a game in C++ using MS Visual Studio 2010. The game is almost at beta state but I'm facing a serious problem here, hopefully someone will be able to help.

So, if I run the game from VS (e.g. with F5 key) everything works perffect. But as soon as I run the newly compiled .exe file of the same game at some points in game I get crashes and some other strange things happen. Is there something I can do to fix it? Is there maybe a certain setting in VS? It's really confusing me, please help if someone knows a solution.

网友答案:

If I remember correctly the F5 key is used to start debugging, and when running in a debugger Visual Studio does things that does not happen when not running in a debugger.

First and foremost the debugger will clear all memory for you, meaning things like uninitialized variables becoming zero. This clearing include uninitialized pointer variables being initialized as null pointers.

If you have uninitialized pointer variables and have null-pointer checks for them, those checks will work fine when running in the debugger, but when not running in a debugger those variables will have an indeterminate value, a value that will be seemingly random and most likely not a null pointer. Thus when you run outside the debugger those non-null pointers will make your program think the pointers are valid and you will dereference them which will lead to undefined behavior.

What you need to do is to go through your code and look for uninitialized variables, especially pointers, and make sure they are properly initialized before you use them.


Like other mention, there are also many other things that can go wrong when running in a different environment than the Visual Studio debugger or by starting the program from Visual Studio. One major problem mentioned is that relative file paths may not be correct any more. The programs working directory when run from the command line at a different directory, or when running by double-clicking its icon, will be different than when started from withing Visual Studio. Having some sort of configuration-value stating things like a base-directory for game assets and other files you need is a good idea. Then you can change the process current working directory to that, or use it to resolve the absolute path for your assets yourself.

分享给朋友:
您可能感兴趣的文章:
随机阅读: