PDA

View Full Version : question about "fortune server"



Dumbledore
13th October 2007, 19:20
Hi, I'm stumped as to of why this code causes my application to crash when I telnet to it. It's almost directly copied from the fortune example here: http://doc.trolltech.com/4.1/network-fortuneserver.html



void send() {
QByteArray block;
QDataStream out(&block, QIODevice::WriteOnly);
out.setVersion(QDataStream::Qt_4_0);
out << (quint16)0;
out << "here's some text i'm sending...";
out.device()->seek(0);
out << (quint16)(block.size() - sizeof(quint16));

QTcpSocket *clientConnection = tcpServer->nextPendingConnection();
connect(clientConnection, SIGNAL(disconnected()),
clientConnection, SLOT(deleteLater()));

clientConnection->write(block);
clientConnection->disconnectFromHost();
}

marcel
13th October 2007, 19:32
Probably because clientConnection is NULL. You don't test for that, yet it is possible for it to be.

And about the byte array: you're writing something to ot, next you're positioning the file pointer to the start of the stream and write something again. The first data gets lost.

Dumbledore
13th October 2007, 19:51
Yeah, like I said it's from an example so I'm trying to learn network programming with QT.

I'm just trying to not crash at this point. This still crashes though:



QByteArray block;
QDataStream out(&block, QIODevice::WriteOnly);
out.setVersion(QDataStream::Qt_4_0);
out << "here's some text i'm sending...";


QTcpSocket *clientConnection = tcpServer->nextPendingConnection();
if ( NULL != clientConnection ) {
connect(clientConnection, SIGNAL(disconnected()),
clientConnection, SLOT(deleteLater()));

clientConnection->write(block);
clientConnection->disconnectFromHost();
}

jpn
13th October 2007, 20:00
Could we see the backtrace from debugger?

marcel
13th October 2007, 20:04
Can't you debug it, to see exactly at what line it crashes?

Dumbledore
13th October 2007, 20:28
I've never used a debugger before. In other words, the code looks fine and something else is going on?

EDIT: Alright I discovered it's because the instance of tcpServer it was using had never been allocated yet. It was a wild pointer. Thanks for the help, normally I don't ask such stupid questions but I'm completely new to this stuff.

marcel
13th October 2007, 20:42
I've never used a debugger before. In other words, the code looks fine and something else is going on?

Code looks good all the time...
You should start using a debugger. These days you can't do any serious programming without one.