David
David

Reputation: 537

Segmentation fault in client program

Simply doing the following results in a segmentation fault. Could it be something with argv or argc? Really lost. Thanks in advance!

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <string.h>
#include <unistd.h>

#define MESSAGE "Not so important message"

int main(int argc, char * argv[])
{
    printf(argc);
    return 0;
}

Upvotes: 0

Views: 284

Answers (2)

c3st7n
c3st7n

Reputation: 1971

I only get a segfault if I don't supply a hostname as an argument. This makes sense as you try to call gethostbyname with the argument of argv[1], which will be a NULL pointer if no argument is supplied.

The reason you don't see any of the printf() messages is that the output is buffered, if you changed them to print to stderr (unbuffered by default) you would see them before the segfault.

Upvotes: 0

Prabhu
Prabhu

Reputation: 3541

if(hp != NULL)
    {
    printf("Here 6");
    perror("Failed to get host by name!");
    exit(1);
    }

Why are you quitting if hp!=NULL ? It should be other way round. You are de-referencing null pointer after this incorrect check:

bcopy((char *)hp->h_addr, (char *) &server.sin_addr.s_addr, hp->h_length)

Change to:

if(hp == NULL)
    {
       perror("Failed to get host by name!");
       exit(1);
    }

Upvotes: 2

Related Questions