How to repair this error of executing? - c++

Every time I compile my simple SDL1.2 code it's compiled successfully
but when I try to run it via terminal (alt+t in Ubuntu):
./game
Segmentation fault (core dumped)
I get this error. Can you help please? This is the code:
#include<SDL/SDL.h>
int main(int argc,char args)
{
SDL_Init( SDL_INIT_EVERYTHING);
SDL_Surface* screen;
screen=SDL_SetVideoMode(640,480,32,SDL_HWSURFACE);
SDL_Flip(screen) ![problem running the program][1];
SDL_Delay(5000);
SDL_FreeSurface(screen);
SDL_Quit();
}

SDL_SetVideoMode returns NULL on error which you do not check for.

Since you're running this via a terminal, I suspect you may have forgotten to tell Xorg to allow running from it. In fact, if this is really the problem it'll prevent any program from running when started that way.
To fix the problem, enter this into the terminal (this only needs to be done once per session):
xhost +
You should get a message that it was successful. I cannot recall the exact message, but it is something like this:
Clients are now allowed to connect from any host.
What was happening (assuming that I was correct regarding xhost) was that the SDL_SetVideoMode() call was failing and returning NULL, because Xorg rejected the connection. Since you're not checking for that, SDL_Flip() ended dereferencing a NULL pointer --- hence the segfault.
SIDE-NOTE: There is an error in your code, however --- namely, you should not call SDL_FreeSurface(screen);; that particular surface is special, and is freed by SDL_Quit(); automatically. Source (see "Return Value" section): http://www.libsdl.org/release/SDL-1.2.15/docs/html/sdlsetvideomode.html

Check if SDL_SetVideoMode() failed!
screen = SDL_SetVideoMode(640, 480, 32, SDL_HWSURFACE);
if (screen == NULL) /* error */;

Run it under valgrind. Or GDB. Or some other debugger of your choice.
You should probably be successfully allocating memory for screen.

Related

QCamera::start gives mysterious "failed to start" log message

It's just plain luck my program is so simple, so I eventually found out what causes the mysterious log message. My program log looks like this:
Debugging starts
failed to start
Debugging has finished
Which happens after:
camera = new QCamera(QCameraInfo::defaultCamera());
// see http://omg-it.works/how-to-grab-video-frames-directly-from-qcamera/
camera->setViewfinder(frameGrabber = new CameraFrameGrabber());
camera->start();
The start() method causes this message in console. Now the meaning of the message is obvious, what it's not very helpful. What steps should I take to troubleshoot it?
Reasons for this might differ, but in my case it was simply because I provided invalid QCameraInfo. The culprit is that QCameraInfo::defaultCamera() might return invalid value if Qt fails to detect any cameras on your system, which unfortunately happens even if cameras are present.

Why would calling MessageBox[etc]() without a return variable cause the program to crash?

So if I write the following code:
MessageBoxA(0, "Yo, wazzup!", "A Greeting From Earth", 0);
the program crashes with an access violation when it exits. When I write the code like this:
int a;
a = MessageBoxA(0, "Yo, wazzup!", "A Greeting From Earth", 0);
it doesn't crash. Now I know why it crashes when it crashes thanks to another question I asked, also regarding argument-mismatching, but I don't know why it crashes.
So why does this cause an APPCRASH? I was always under the impression that calling a function that had a return-type, without actually giving one was safe, example:
int SomeFunction (void) {
std::cout << "Hello ya'll!\n";
return 42;
}
int main (void) {
int a;
// "Correct" ?
a = SomeFunction();
a = MessageBoxA(0, "Yo, wazzup!", "A Greeting From Earth", 0);
// "Incorrect" ?
SomeFunction();
MessageBoxA(0, "Yo, wazzup!", "A Greeting From Earth", 0);
}
When I run this kind of test "clean" (in a new file) I don't get any errors. It only seems to give an error with MessageBox/MessageBoxA when run in my program. Knowing the possible causes would help me pinpoint the error as the project code is too big to post (and I would need my friend's permission to post his code anyway).
Additional Info:Compiler = GCCPlatform = Windows
EDIT:
UpdateThanks everyone for your feedback so far. So I decided to run it through a debugger... Now Code::Blocks doesn't debug a project unless it is loaded from a project file (*.cbp) - AFAIK. So I created an actual project and copy-pasted our project's main file into the projects. Then I ran in debug mode and didn't get so much as a warning. I then compiled in build mode and it ran fine.Next, I decided to open a new file in Dev-C++ and run it through the debugging and later the final build process and again I got no errors for either build or debug. I cannot reproduce this error in Dev-C++, even with our main file (as in the one that causes the error in Code::Blocks).
ConclusionThe fault must lie in Code::Blocks. AFAIK, they both use GCC so I am pretty confused. The only thing I can think of is a version difference or perhaps my compiler settings or something equally obscure. Could optimizer settings or any other compiler settings somehow cause this kind of error?
The version with the return value does not crash because it had one int more on the stack. Your erroneous code reads over the bounds of the stack and then runs into an access violation. But if you have more on the stack you will not hit the guard page, because that is just enough extra stack. If the the erroneous code only reads it is sort of OK, but still broken.
We had one bit of WTF inducing code that was like so:
char dummy[52];
some_function();
There was thankfully a longish comment explaining that removing dummy, makes some_function crash. It was in a very old application so nobody dared touch it and the some_function was totally different module we had no control over. Oh yea and that application was running smoothly in the field for over 20 years in industrial installations, like refineries or nuclear power plants... ^_^

Pointer Error Debugging Help

I am new to C++, and I am trying to program a replica of Pong using freeglut with Visual Studio 2010. My code was working fine until I made some revisions to it in order to make it more object oriented. When I ran it again, it worked a couple times, until I made some minor edit (to be honest, I can't remember what it was that I changed, since I only built my code the next morning), and I received this runtime error as soon as I ran the program:
Unhandled exception at 0x1000bbae in Pong.exe: 0xC0000005: Access violation writing location 0x000000a8.
I'm not particularly good at debugging, but I believe this is coming at the line glutDisplayFunc() in my main loop. I think this has something to do with null pointers, but I have no idea what. Could somebody help me find my problem?
Below is the applicable portion of my program (Main.cpp):
include "header.h"
using namespace std;
int main(int argc, char** argv) {
//Initialize GLUT
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);
glutInitWindowSize(WIDTH, HEIGHT); //Set the window size
//Create the window
//modesetup(2);
//Set handler functions for drawing, keypresses, and window resizes
glutDisplayFunc(mainDraw);
glutKeyboardFunc(handleKeypress);
glutKeyboardUpFunc(handleKeyup);
glutSpecialFunc(handleSpecial);
glutSpecialUpFunc(handleSpecialUp);
glutReshapeFunc(handleResize);
glutTimerFunc(25, update, 0);
glutMainLoop(); //Start the main loop. glutMainLoop doesn't return.
return 0; //This line is never reached
}
Thanks in advance!
EDIT: I just made a new program that uses very standard functions for everything, but I still get this error. I'm beginning to think that there may be something wrong with my freeglut installation.
Use F5 to run the program with debugging in visual studio. When you get the error the debugger should place you right on the line with the illegal access. If it doesn't have source code for the location then check up the call stack.
Cheers & hth.
Run your program under valgrind. It will give you a lot more information about the problem, and might even point out memory errors other than the immediate cause of the crash.
You probably already solved the problem. But since I had the same problem and couldn t find an answer two it anywhere I will answer the question:
You simply forgot to write the
glutCreateWindow("Windowname");
function before the
glutDisplayFunc(mainDraw);
glutKeyboardFunc(handleKeypress);
glutKeyboardUpFunc(handleKeyup);
glutSpecialFunc(handleSpecial);
glutSpecialUpFunc(handleSpecialUp);
glutReshapeFunc(handleResize);
glutTimerFunc(25, update, 0);
part.
This leads to the exception you get.

OUTDATED - Error modes for OpenCV

I am using OpenCV 1 to do some image processing, and am confused about the cvSetErrMode function (which is part of CxCore).
OpenCV has three error modes.
Leaf: The program is terminated after the error handler is called.
Parent: The program is not terminated, but the error handler is called.
Silent: Similar to Parent mode, but no error handler is called
At the start of my code, I call cvSetErrMode(CV_ErrModeParent) to switch from the default 'leaf' mode to 'parent' mode so my application is not terminated with an exception/assertion pop up.
Unfortunately 'parent' mode doesn't seem to be working. I still get the message dialog pop up, and my application still terminates.
If I call cvSetErrMode(CV_ErrModeSilent) then it actually goes silent, and no longer quits the application or throws up a dialog... but this also means that I dont know that an error has occurred. In this case, I think the mode is being set correctly.
Has anyone else seem this behaviour before and might be able to recommend a solution?
References:
cvSetErrMode function reference
Open CV Error handling mode reference
I am going to answer my own question, because after some fiddling around I have worked out what happens.
When you switch to 'parent' mode instead of leaf mode, there is an error handler that gets called cvGuiBoxReport(). cvGuiBoxReport() is the default error handler. It seems that even in parent mode, cvGuiBoxReport() still terminates your application! Oops.
So, to get around that you can write your own error handler, and redirect the error to be handled and NOT terminate the application.
An example error handler:
int MyErrorHandler(int status, const char* func_name, const char* err_msg, const char* file_name, int line, void*)
{
std::cerr << "Woohoo, my own custom error handler" << std::endl;
return 0;
}
You can set up parent mode and redirect your error with:
cvSetErrMode(CV_ErrModeParent);
cvRedirectError(MyErrorHandler);
In a week of servers crashing from uploading corrupt or empty images to our image processing server, here are some thoughts on how I solved the intricacies of OpenCV's error handling. We are using V2.2 in a C++ server.
The problem arises in cv::imread() and cv::imdecode() when the image to be loaded is corrupt (or empty). Normally OpenCV just exits the process with with some error messages, not a good idea when you're running a server which should work all the time.
Reviewing the source code at https://code.ros.org/trac/opencv/browser/trunk/opencv/modules/core/include/opencv2/core/core.hpp I ignored the hint in the source comments for cv::setBreakOnError() and discovered the that following pattern works:
cv::setBreakOnError(true); // Can be set globally
...
...
cv::Mat srcImage = cv::imread(filename, 1);
if (!srcImage.data) throw std::exception("bad image");
cv::imread() will now not exit the process, but passes control to your own exception handling, so you can do with it what you like.
Finding this has saved a lot of heartbreak.

SwapBuffers crashing my program!

I have an OpenGL program that works on all of my computers but one. It's a desktop with Vista 64 and a Radeon HD4850. The problem seems to be in my call to SwapBuffers(hdc).
It compiles fine and then gives me an exception:
Unhandled exception at 0x00000000 in Program.exe: 0xC0000005: Acces violation.
Using VC++ to break before the call to SwapBuffers shows hdc's value to be:
0xfe011734 {unused=???}
CXX0030: Error: expression cannot be evaluated
Anyone have a clue what could be happening? Is there something about SwapBuffers that would change from one PC to the next? I've gotten it to work on XP32, XP64 and a (different) Vista64.
while (!quit)
{
if (PeekMessage(&msg, NULL, NULL, NULL, PM_REMOVE))
{
if (msg.message == WM_QUIT)
quit = true;
TranslateMessage(&msg);
DispatchMessage(&msg);
}
renderFrame(); //draws the scene
SwapBuffers(hdc);
if (GetAsyncKeyState(VK_ESCAPE))
shutdown();
think(); //calculates object positions, etc.
}
The drivers on the problematic system (HD4850) are up-to-date. I've run, and wrote, the program on another Vista64 system with a Radeon HD4870, also with up-to-date drivers. As far as I know, the drivers for these two cards are nearly identical as both are in the HD48xx series. For that reason it seems odd that the GPU is causing the problem.
Anyway, am I wrong or is this a memory issue? (Access violation)
Also, if I remove the call to SwapBuffers(hdc), the program runs seemingly well, although nothing is drawn, of course, because the framebuffers are never swapped. But it is at least stable.
Call stack (-> is stack ptr):
ATKOGL32.dll!6aef27bc()
opengl32.dll!665edb2d()
opengl32.dll!665f80d1()
gdi32.dll!75e14104()
-> MyProg.exe!WinMain(HINSTANCE__ * hinstance=0x009a0000, HINSTANCE__ * hprevinstance=0x00000000, char * lpcmdline=0x003b4a51, int nshowcmd=1) Line 259 + 0xe bytes
MyProg.exe!__tmainCRTStartup() Line 578 + 0x35 bytes
MyProg.exe!WinMainCRTStartup() Line 400
kernel32.dll!7641e3f3()
ntdll.dll!777dcfed()
ntdll.dll!777dd1ff()
Heres the assembly (-> is the next instruction to be executed):
SwapBuffers(hdc);
009B1B5C mov esi,esp
009B1B5E mov eax,dword ptr [hdc (9BF874h)]
009B1B63 push eax
009B1B64 call dword ptr [__imp__SwapBuffers#4 (0E1040Ch)]
-> 009B1B6A cmp esi,esp
009B1B6C call #ILT+780(__RTC_CheckEsp) (9B1311h)
It looks like you could be accessing the HDC after the window has been destroyed, does the problem disappear if you break out of the loop as soon as you get WM_QUIT ?
This is almost definitely a bug in the drivers. The reason why you can't see the value of hdc is because the top stackframe for the crash is actually inside ATKOGL32.dll but since there are no symbols for that the debugger shows you your code. As far as I can tell ATKOGL32.dll is actually an ASUS wrapper for the ATI driver and that's where the crash happens. You might want to install stock ATI drivers from amd.com and see if the crash still persists.
While the driver should never crash no matter what series of OpenGL calls you make, in my experience usually the crashes are the result of some kind of invalid call that your program makes. Technically this should just be ignored and the error state set but thats not always what happens. You can check for any invalid OpenGL calls easily by using a program like gDebugger.
Whatever hdc is set to, it doesn't look to be a proper value. Is the window created before this call? Is there any multithreading involved with this application that could hurt hdc?
Try creating a watch on the address of hdc itself, and see when the value is changed to be an invalid location, that might give you a hint as to where it changes.
We had the same (or at least very similar) issue. It turns out the Dell Nahimic service and Asus Sonic Suite use some weird injection code.
For us the problem solved itself after disabling these services.
Source: https://github.com/glfw/glfw/issues/1682