Search code examples
c++csocketssegmentation-faultbsd

Seg Fault on getaddrinfo()


I am getting a segmentation fault on my getaddrinfo call and cannot figure out why. It happens on both my server and client. Some code (server side) is -

class TcpServer {
public:

    TcpServer(int);
    ~TcpServer();

    void launchServer();

    void communicate();

private:
    const char* port;
    int fd;
    int comm_fd;
};

in tcpserver.cpp-

void TcpServer::launchServer() {
    int status;

    struct addrinfo hints;
    struct addrinfo *servinfo;  //will point to the results

    //store the connecting address and size
    struct sockaddr_storage their_addr;
    socklen_t their_addr_size;

    //socket infoS
    memset(&hints, 0, sizeof hints); //make sure the struct is empty
    hints.ai_family = AF_INET;  //local address
    hints.ai_socktype = SOCK_STREAM; //tcp
    hints.ai_flags = AI_PASSIVE;     //use local-host address

    //get server info, put into servinfo
    if ((status = getaddrinfo("127.0.0.1", port, &hints, &servinfo)) != 0) {
        fprintf(stderr, "getaddrinfo error: %s\n", gai_strerror(status));
        exit(1);
    }

in main-

TcpServer server(4950);
server.launchServer();

The int passed to the constructor is casted to a const char* for port.

When I run gdb, it gives me a backtrace of -

#0  0xb7dca737 in getaddrinfo (name=0x8054824 "127.0.0.1", 
    service=0x1356 <Address 0x1356 out of bounds>, hints=0xbffff20c, 
    pai=0xbffff234) at ../sysdeps/posix/getaddrinfo.c:2080
#1  0x08050f79 in TcpServer::launchServer (this=0xbffff304) at tcpserver.cpp:25
#2  0x0804eae9 in main (argc=1, args=0xbffff3f4) at mainserver.cpp:47

So "Address 0x1356 out of bounds" makes me believe something is wrong with port, but I do not know what could be wrong. If anyone can point out something wrong I would be grateful. Thanks for any help.


Solution

  • getaddrinfo("127.0.0.1", port, &hints, &servinfo)
                              ^
    

    That should be a char *. I am guessing you are passing an integer and forcing the library to access an invalid address.

    EDIT

    In light of the comment of Blagovest Buyukliev I believe you are doing something like this in the constructor: this->port = (const char*) port.

    You need to use something (snprintf maybe ?) to convert that integer to a char *. Simply casting won't do.