EDIT: I changed the title because it suited not nearly the problem, as the new operator was not the problem. The formerly title was “Can operator new fail?”
In the code below, before a client connects to the server I create a new Socket object pointer. When a client connects I create the object with new. But somehow when I step through the code with the debugger (Eclipse CDT, g++ Ubuntu/Linaro 4.6.3-1ubuntu5) I see that after the call of the new operator the pointer ist still NULL.
class Socket
{
public:
Socket( int domain, int type, int protocol = 0 );
~Socket();
[...]
int accept( Socket * socket );
[...]
private:
Socket();
int mSocketDescriptor;
int mNetworkProtocol;
int mTransportProtocol;
};
[...]
int Socket::accept( Socket * socket )
{
// Accept one connection (blocking)
struct sockaddr_in cli_addr;
socklen_t clilen = sizeof(cli_addr);
int ret = ::accept(mSocketDescriptor, (struct sockaddr *) &cli_addr, &clilen);
if ( ret >= 0 ){
socket = new Socket(); // <- Here's the problem, socket remains NULL
socket->mSocketDescriptor = ret;
socket->mNetworkProtocol = this->mNetworkProtocol;
socket->mTransportProtocol = this->mTransportProtocol;
}
return ret;
}
Mainloop:
// Accept all incoming connections in a loop
while(true){
// Accept one connection (blocking)
net::Socket * newConn = NULL;
if (socket.accept(newConn) < 0){
perror("accept()");
exit(EXIT_FAILURE);}
// Create a new thread that is talking to the client
pthread_t nThreadID;
pthread_create(&nThreadID, NULL, ClientMainThreadProc, newConn);
}
I read through the C++ reference. It tells me that a bad_alloc exception should araise if the new fails. But that is not the fact so I have no idea whats going wrong. Any suggestions?
Okay the solution to the problem is, as hmjd stated:
Unfortunately my debugger steered me in the wrong direction, showing the socket pointer note even change locally. But when pass the pointer by reference everthing works fine.