yOmar
yOmar

Reputation: 11

C DNSlookup throwing Segmentation fault

Any ideas why this DNS lookup program is throwing a "Segmentation fault: 11"?

I've found that it's to do with being out of allocated memory, but don't know where that's occurring.

Thanks.

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <errno.h>
#include <netdb.h>
#include <arpa/inet.h>

int main()
{
    int sockfd;
    struct addrinfo hints, *results, *p;
    struct sockaddr_in *ip_access;
    int rv;
    char *hostname;
    char ip[100], inputVal[100];

    printf("Enter a domain name: \n");
    scanf("%s", inputVal);

    strcpy(hostname, inputVal);

    memset(&hints, 0, sizeof hints);
    hints.ai_family = AF_UNSPEC;
    hints.ai_socktype = SOCK_STREAM;

    if((rv = getaddrinfo(hostname, "domain", &hints, &results)) != 0)
    {
    fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv));
    return 1;
    }

    // loop through structure using ai_next
    for(p= results; p != NULL; p = p->ai_next)
    {
        // pass data into sockaddr in struct
        ip_access = (struct sockaddr_in *) p->ai_addr;

        printf("IP address is %s: \n", inet_ntoa(ip_access->sin_addr));
    }
    freeaddrinfo(results);

    printf("\n");
}

Upvotes: 0

Views: 401

Answers (2)

yano
yano

Reputation: 5285

hostname is uninitialized, you're not allocating any space for it, so strcpy(hostname, inputVal); invokes undefined behavior. You can solve this by allocating space for it, either dynamically:

char *hostname = malloc(100);
if (hostname == NULL)
{
  // you can handle this error anyway you like, this is just an example
  fprintf(stderr, "Out of memory\n");
  exit(-1);
}
...
// after you're done using hostname, cleanup
free(hostname);

or you can assign space for it in automatic storage as you have done with ip and inputVal:

char hostname[100];

I prefer the automatic storage solution in this example. In fact I would probably get rid of inputVal altogether and just do

char hostname[100];
scanf("%99s", hostname);  // %99s ensures only 99 characters of data will be read from stdin,
                          // leaving room for the NUL terminator. Hostnames can get
                          // long, so you may want more than 100 characters.

and go from there.

Upvotes: 2

bebidek
bebidek

Reputation: 592

You don't need inputVal array at all as you scanf only one string. Use char hostname[100] instead and segfault should disappear.

Upvotes: 1

Related Questions