user3032010
user3032010

Reputation: 47

Segmentation fault in thread

I have written a server program which has two threads. One thread receives data from client and the other thread sends data to the client. Both threads consist of an infinite loop to send and receive data.

My problem is, the server accepts the connection and creates thread for sending data, but, I get a segmentation fault and the server terminates. Why?

The code of the sending thread is:

void *send_data(void *num)
{
    int *sock_s=(int *) num;
    int sock=*sock_s;
    char msg[50];
    while(1)
    {
        fgets(msg,50,stdin);
        printf("sending data");
        if(strcmp(msg,"exit")==0)
        {
            break;
        }
        send(sock,msg,sizeof(msg),0);
    }
    send(sock,msg,strlen(msg),0);
}

The above thread is created by:

status_s=pthread_create(&thread_s,NULL,send_data,(void *)client_sock);

Upvotes: 0

Views: 1081

Answers (1)

K Scott Piel
K Scott Piel

Reputation: 4380

You are passing in the client socket, not a pointer to the client socket. You are treating num as a pointer, so you are trying to "read" from a memory address that is likely a value like 3 or 4 or 5 (the socket ID, an index into the file descriptor table)... and that's a memory violation.

It should be...

void *send_data( void *num )
{
    int sock = (int)num;
    ...

Upvotes: 3

Related Questions