'SDL_main' : must return a value - c++

I am trying to retreive content of websice in c++ usind SDL but it is giving me this error:
'SDL_main' : must return a value
my code is:
#include <iostream>
#include "SDL.h"
#include "SDL_net.h"
#include <cstring>
int main(int argc,char** argv)
{
SDL_Init(SDL_INIT_EVERYTHING);
SDLNet_Init();
IPaddress ip;
SDLNet_ResolveHost(&ip,"www.linux.org",80);
const char* http="GET / HTTP/1.1\nHost: www.linux.org\n\n";
TCPsocket client=SDLNet_TCP_Open(&ip);
SDLNet_TCP_Send(client,http,strlen(http)+1);
char text[10000];
while(SDLNet_TCP_Recv(client,text,10000))
std::cout << text;
SDLNet_TCP_Close(client);
SDLNet_Quit();
SDL_Quit();
}
When I put return 0; at the end, it built project but it finished immediately after that
(I am using vs2012)
UPDATE
cout<<"Some message";
doesn't print anything, is it possible that I have configured my imports wrong? are those additional dependencies right?
SDL.lib;SDL_net.lib;SDLmain.lib
I don't know what else could be wrong ...

It's because SDL defines a macro like this:
#define main SDL_main
So the function you've written is actually called SDL_main and like any other function that is not the actual main function, if it doesn't return void, you have to give it a return statement.

because your code doesn't loop forever it just returns 0 after first pass, you need to make a loop like:
while(1){
sdl_events event;
switch(event){
//handle events, drawings and so on
...
...
...
case SDL_QUIT:
exit (0);
break;
}
}
http://sdl.beuc.net/sdl.wiki/OpenGL_Full_Example
UPDATE
you may also have some problem connecting to host so you could check if connection succeed like this:
#define MAXLEN 1024
int result;
char msg[MAXLEN];
result = SDLNet_TCP_Recv(sock,msg,MAXLEN-1);
if(result <= 0) {
// TCP Connection is broken. (because of error or closure)
SDLNet_TCP_Close(sock);
exit(1);
}
else {
msg[result] = 0;
printf("Received: \"%s\"\n",msg);
}
UPDATE 2
change this:
while(SDLNet_TCP_Recv(client,text,10000))
std::cout << text;
to this:
while(SDLNet_TCP_Recv(client,text,9999))
std::cout << text;
UPDATE 3
try this, put your receive part in this if statement
if(SDLNet_SocketReady(client) == 1)
{
while(SDLNet_TCP_Recv(client,text,9999))
std::cout << text;
}
if this still doesn't work I suggest to use QT sockets or Boost asio, both async and more intuitive

Related

Knowing where is the segmentation fault happening comparing two files

I have the following structure:
int main(int argc, char **argv) {
try {
FX3USBConnection fx3USB3Connection = FX3USB3Connection();
fx3USB3Connection.send_text_file();
}
catch (ErrorOpeningLib& e) {
printf("Error opening library\n");
return -1;
}
catch (NoDeviceFound& e) {
printf("No device found\n");
return 0;
}
return 0;
}
Within send_text_files, the last thing I do is compare two txt files as follows:
printf("Loopback recieved, checking if I received the same that I sended\n");
files_match(out_text_filename, in_text_filename);
printf("Exited without problem");
return; // (actually implicit)
I already used 2 version of files_match function but the last one is an exact copy of this Compare two files
bool FX3USB3Connection::files_match(const std::string &p1, const std::string &p2) {
bool files_match;
std::ifstream f1(p1, std::ifstream::binary|std::ifstream::ate);
std::ifstream f2(p2, std::ifstream::binary|std::ifstream::ate);
if (f1.fail() || f2.fail()) {
return false; //file problem
}
if (f1.tellg() != f2.tellg()) {
return false; //size mismatch
}
//seek back to beginning and use std::equal to compare contents
f1.seekg(0, std::ifstream::beg);
f2.seekg(0, std::ifstream::beg);
files_match = std::equal(std::istreambuf_iterator<char>(f1.rdbuf()),
std::istreambuf_iterator<char>(),
std::istreambuf_iterator<char>(f2.rdbuf()));
f1.close();
f2.close();
if (files_match) { printf("Files match\n"); }
else { printf("Files not equal\n"); }
return files_match;
}
Sometimes I get an error and sometimes I don't. When I get the error I get:
Loopback recieved, checking if I received the same that I sended
Files match
Process finished with exit code 139 (interrupted by signal 11: SIGSEGV)
So, the print after the call to files_match is not being print so I guess the problem was within the function. However, I do a print just before the return statement and it is printing correctly.
PS: I commented the function files_match and I have no problems.
PS1: The files can have whatever like this character: ¥
Yes, as #john suggested, I had to add the fflush() function. There I realize the error was actually outside all this loop but actually is when getting out of the try{} section. It seams to me that is not managing to destroy the fx3USBConnection.
Thank you! I was so mislead now knowing fprint was actually buffered.

I can't create server application in RakNet ( C++ )

I'm trying create server application in C++ using RakNet.
When i try following code :
#include <stdio.h>
#include "RakPeerInterface.h"
#define MAX_CLIENTS 10
#define SERVER_PORT 60000
int main(void)
{
char str[512];
RakNet::RakPeerInterface *peer = RakNet::RakPeerInterface::GetInstance();
bool isServer;
printf("(C) or (S)erver?\n");
gets(str);
if ((str[0] == 'c') || (str[0] == 'C'))
{
SocketDescriptor sd;
peer->Startup(1, &sd, 1);
isServer = false;
}
else {
SocketDescriptor sd(SERVER_PORT, 0);
peer->Startup(MAX_CLIENTS, &sd, 1);
isServer = true;
}
// TODO - Add code body here
RakNet::RakPeerInterface::DestroyInstance(peer);
return 0;
}
Compiler giving this errors :
I guess i set up RakNet successfully What is missing ?
Well, one that that seems to be missing - if you are using the RakNet SocketDescriptor object is the "RakNet::" part to elt it know which namespace to use?
You have it on the PeerInterface section, but then have not used it on the SocketDescriptor
Also the RakNet socket descriptors are part of the "#include "RakNetTypes.h"" as far as I remember.. which also seems to be missing.. so unless youre using other SocketDescriptors .. that may also be needed :o
Missed the "Gets" part too - there is header for that under "#include "Gets.h"" within Raknet as well

How to register custom exception in Intel SGX?

I'm having difficulty to get my custom exception handler to work.
This is the Enclave code:
#include "Enclave_DivideZero_t.h"
#include "sgx_trts_exception.h"
#include "sgx_trts.h"
#include <string>
static char buf[200] = "Handler not called";
int divide_by_zero_handler(sgx_exception_info_t* info) {
buf[0] = '1';
return EXCEPTION_CONTINUE_EXECUTION;
}
void Enclave_DivideByZero() {
Ocall_printf(buf);
if (sgx_register_exception_handler(1, divide_by_zero_handler) == NULL) {
Ocall_printf("register failed");
} else {
Ocall_printf("register success");
}
int a(1);
int b(3/(a-a));
(void) a;
(void) b;
Ocall_printf(buf);
}
We used buf as an indication of whether the handler has been actually executed. However, the output is this:
Enclave created!
[Ocall printf] - Handler not called
[Ocall printf] - register success
[Ocall printf] - Handler not called <-- should be: "1andler not called" ("1andler" instead of "Handler")
Also, here is the App code (i.e. the untrusted code)
#include "stdafx.h"
#include "sgx_urts.h"
#include "Enclave_DivideZero_u.h"
#define ENCLAVE_FILE _T("Enclave_DivideZero.signed.dll")
sgx_status_t createEnclave(sgx_enclave_id_t *eid) {
sgx_status_t ret = SGX_SUCCESS;
sgx_launch_token_t token = {0};
int updated = 0;
ret = sgx_create_enclave(ENCLAVE_FILE, SGX_DEBUG_FLAG, &token, &updated, eid, NULL);
return ret;
}
void Ocall_printf( char* str) {
printf("[Ocall printf] - %s\n", str);
}
int _tmain(int argc, _TCHAR* argv[]) {
sgx_enclave_id_t eid;
sgx_status_t res = createEnclave(&eid);
if (res != SGX_SUCCESS) {
printf("App: error-, failed to create enclave.\n");
return -1;
} else {
printf("Enclave created!\n");
}
Enclave_DivideByZero(eid);
return 0;
}
The Problem: As you can see from the output indicates that the handler is registered successfully, but is not executed.
1- Why the registration doesn't work?
2- I tried to put the registeration with the App code, and for this I had to add the handler in the edl, the problem for this is passing the sgx_exception_info_t *info param, which is not clear which flags it needs (i.e. [in, .. <'flags'>]). So, is it correct to define it inside the Enclave?
p.s. I ran the code with Prerelease Mode.
[EDIT] I documented the project + code that I conducted on SGX here
So the question is a bit old now, but I got stuck at the same place, so maybe someone can still use my insight.
In trts_veh.cpp, where it is checked whether the exception was handled, it says in a comment that the "instruction triggering the exception will be executed again". This leads to the exception handling loop, as you noticed yourself.
However, you can increase the rip yourself, as it is stored in the pointer to the sgx_exception_info_t, by using "info->cpu_context.rip += 2;". Adding this inside your exception handler should do the trick.

Qt Creator crashes when using multiple threads

I'm writing a Qt (5.3) program which has a joystick test UI in it, but I need a separate thread for an infinite while loop looking for joystick axis/button value changes through SDL. That part of the code is working fine as I can have the thread qDebug() messages and it seems to work. But from the main window, when I try to open the test joystick UI, the program crashes. I've had the test joystick UI running separation WITHOUT the JoystickThread thread and it seems to open up fine.
The error messages are inconsistent though - some times, I just get
The program has unexpectedly finished.
/home/narendran/QtWorkspace/build-LinkControl-Desktop-Debug/LinkControl crashed
This has shown up once:
QXcbWindow: Unhandled client message: "_GTK_LOAD_ICONTHEMES"
And a few other times:
[xcb] Unknown sequence number while processing queue
[xcb] Most likely this is a multi-threaded client and XInitThreads has not been called
[xcb] Aborting, sorry about that.
star: ../../src/xcb_io.c:274: poll_for_event: Assertion `!xcb_xlib_threads_sequence_lost' failed.
I found that this was common if XInitThreads(); is not run in the main function, but even with it on there, it crashes with the same error(s).
main.cpp
#include <qsplashscreen.h>
#include "linkcontrol.h"
#include "configure.h"
#include <unistd.h>
#include <QApplication>
#include <QPixmap>
#include <QStyle>
#include <QDesktopWidget>
#include "linkports.h"
#include "joystickthread.h"
#include <X11/Xlib.h>
int main(int argc, char *argv[])
{
XInitThreads();
QApplication a(argc, argv);
QPixmap pix(":splash.png");
QSplashScreen splash(pix);
splash.show();
a.processEvents();
JoystickThread jsThread;
jsThread.start();
LinkControl linkcontrol;
usleep(1000000);
splash.finish(&linkcontrol);
usleep(100000);
linkcontrol.show();
linkcontrol.setGeometry(QStyle::alignedRect(Qt::LeftToRight, Qt::AlignCenter,linkcontrol.size(),a.desktop()->availableGeometry()));
return a.exec();
}
The actual thread is in joystickthread.cpp
#include "joystickthread.h"
#include "global.h"
#include "unistd.h"
/* JoystickThread::JoystickThread(int _interval)
{
this->interval_us = _interval;
} */
void JoystickThread::run()
{
while(1)
{
if(joystick->connected)
{
joystick->updateJSData();
// Check for changed values
for(int i=0; i<joystick->axis.count(); i++)
{
if(joystick->axis.value(i) != joystick->axis_last[i])
{
joystick->axisUpdateEmit(i);
// qDebug() << "AXIS: " << i << "\tVALUE: " << joystick->axis.value(i);
}
joystick->axis_last[i] = joystick->axis.value(i);
}
for(int i=0; i<joystick->button.count(); i++)
{
if(joystick->button.value(i) != joystick->button_last[i])
{
joystick->btnUpdateEmit(i);
// qDebug() << "BUTTON: " << i << "\tVALUE: " << joystick->button.value(i);
}
joystick->button_last[i] = joystick->button.value(i);
}
}
usleep(2500);
}
}
The function that causes the program to crash is in linkcontrol.cpp
void LinkControl::on_actionJoystick_Test_triggered()
{
qDebug() << "STARTING CHECK";
if(!js_test->initialized) {
qDebug() << "NOT INIT";
js_test = new TestJoystick();
js_test->initialized = true;
qDebug() << "FININSH INIT";
}
if(joystick->connected) {
qDebug() << "SHOWING UI";
js_test->show();
} else {
QMessageBox::critical(this, tr("No Joystick Connected!"), tr("Please connect a joystick first..."));
}
}
Where js_test is declared as a TestJoystick object in the linkcontrol.h file
public:
explicit LinkControl(QWidget *parent = 0);
QSlider *portSliders[16];
QLineEdit *setVals[16];
SerialTerminal *ser_term;
TestJoystick *js_test;
~LinkControl();
Thank you very much! Please let me know if you need anymore information.
QThreads are a little tricky to get used to initially, and have their share of gotchas.
You should construct and connect appropriate items at the top of your run function.
If you do it other places, you need to make sure that you don't use Qt::AutoConnection, but instead use Qt:QueuedConnection.
http://qt-project.org/doc/qt-5/qt.html#ConnectionType-enum
Certain elements are only accessible from the "GUI" thread or the main thread of the program. This is the thread that has QApplication::exec(); ran on. It has an event loop that propagates messages around.
Look at the Application output for runtime errors that Qt will tell you about.
When crossing thread boundaries, be sure to use signals and slots.
And if you are accessing a member of your thread class from outside that thread, be sure to use thread synchronization, practices, such as prefacing all access to these members with QMutexLocker locker(m_mutex);.
http://qt-project.org/doc/qt-5/threads.html
And as implied by the title "GUI thread", it is the only thread that is allowed to do certain things such as drawing QPixmaps and accessing certain parts of QWidgets.
Hope that helps.

Windows Semaphore and QSystemSemaphore

I have a problem with semaphores in Windows between two application. An application waits for release signal(Qt) and the other application sends release signal(MSVC2008). But it dose not work.
I tested Qt-Qt and MSVC2008-MSVC2008 modes and they was succeed. But when I try Qt-MSVC2008 mode it fails.
// MSVC2008:
#include <windows.h>
#include <stdio.h>
int main()
{
const WCHAR semName[] = L"TestSem";
PHANDLE sem = (HANDLE *) CreateSemaphore (NULL, 0, 1, semName);
if (sem == NULL)
{
sem = (HANDLE *)OpenSemaphore (SEMAPHORE_ALL_ACCESS, 0, semName);
}
if (sem == NULL)
{
printf("OPEN/CREATE ERROR\n");
return 0;
}
BOOL r = ReleaseSemaphore(sem, 1 ,NULL);
if (r)
printf("OK\n");
else
printf("RELEASE ERROR\n");
CloseHandle (sem);
return 0;
}
and
// Qt 4.8.0 :
#include <QSystemSemaphore>
#include <QCoreApplication>
#include <iostream>
int main()
{
QSystemSemaphore *sem_read = new QSystemSemaphore("TestSem");
std::cout << "Wait for signal: " << std::endl;
while (1)
{
sem_read->acquire();
std::cout << "Hi" << std::endl;
}
return 0;
}
I expect when Qt-app is running, after executing MSVC2008-app, it prints one "Hi" in the screen. But it dose not. What is the problem?!
Note: I'm using Windows 7 and MinGW compiler for Qt
Looking at the Qt sources (4.7.3) I see at corelib/kernel/qsystemsemaphore_p.h:79 that the semaphore name generated by Qt is prefixed by qipc_systemsem_.
[UPDATE] The sha1 hash of "TestSem" is also appended, so the resulting Qt semaphore name is qipc_systemsem_TestSem3ec37c26f212774998f34a4e6722cac152ad17fa
Confirmed working.
To generate the semaphore name:
QString prefix = "qipc_systemsem_";
QString key = "TestSem";
QString result = prefix;
QString part1 = key;
part1.replace(QRegExp(QLatin1String("[^A-Za-z]")), QString());
result.append(part1);
QByteArray hex = QCryptographicHash::hash(key.toUtf8(), QCryptographicHash::Sha1).toHex();
result.append(QLatin1String(hex));
qDebug() << result;
2 things I'd look into:
QSystemSemaphore requires an initial values and initiated with 0 if it is not given. Maybe start it with 1?
this is a system semaphore, could it be that your first test did not release it? try to change the name maybe.