I am receiving a segmentation fault (core dumped) when I execute the following code.
I am having difficulty determining why I am getting this error. I'm thinking it's a pointer issue.
Here is the code
struct info{
char *host;
char *channel;
char *user;
}Ainfo;
int main(int argc, char *argv[])
{
struct addrinfo hints;
struct addrinfo *result, *result2;
int sock,getadd;
Ainfo.host=argv[2];
if(argc<3)
{
perror("too few Arguments\n");
exit(0);
}
memset(&hints, 0, sizeof(struct addrinfo));
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_DGRAM;
hints.ai_flags = 0;
hints.ai_protocol = 0;
getadd=getaddrinfo(Ainfo.host,PORT,(struct addrinfo *)&hints,&result);
if(getadd!=0){
perror("\n");
exit(0);
}
return 0;
}
Transferring key comments into an answer.
What is PORT
defined as? POSIX says getaddrinfo()
has the prototype
int getaddrinfo(const char *restrict nodename, const char *restrict servname, const struct addrinfo *restrict hints, struct addrinfo **restrict res);
and also stipulates:
The
nodename
andservname
arguments are either null pointers or pointers to null-terminated strings. One or both of these two arguments shall be supplied by the application as a non-null pointer.
The OP notes:
#define PORT 6667
If you have #define PORT 6667
, then that does not look like either a null pointer or a null-terminated string. So it isn't a big surprise (to me) that your code is crashing.
It is a surprise that you are not getting compiler warnings telling you that you're doing it wrong. Get the warnings enabled, or get a better compiler. And heed the warnings — the compiler knows more about C than you do. I rarely run code that doesn't compile cleanly with
gcc -O3 -g -std=c11 -Wall -Wextra -Werror -Wmissing-prototypes -Wstrict-prototypes …
(The -Werror
makes sure I deal with the warnings because the compilation fails if there are any! I sometimes add some more warnings; I rarely remove any of them.)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.