Operating System - HP-UX
1828028 Members
1891 Online
109973 Solutions
New Discussion

Memory fault at run time in C program

 
SOLVED
Go to solution
Matias Di Blasi
New Member

Memory fault at run time in C program

This code convert a ip address in decimal dot notation to hexadecimal, it work fine in linux but when i test in HP-UX i get "Memory fault". It compiled fine.

#include
#include

main(int argc, char *argv[])
{
struct in_addr *ip;

if (argc!=2)
{ printf("inet_atoh \n");
exit();
}

if (inet_aton(argv[1],ip))
printf("%x\n",ntohl(ip->s_addr));
}
Is there something wrong with the above code?
Thank you in advance for any help.
Matias Di Blasi
3 REPLIES 3
H.Merijn Brand (procura
Honored Contributor

Re: Memory fault at run time in C program

a5:/tmp 103 > cc -O -o xx xx.c
cc: line 14: warning 5004: Uninitialized variable "ip" in function "main" (5004)
a5:/tmp 104 > ./xx 192.193.194.195
0
Exit 2
a5:/tmp 105 > gcc -O -o xx xx.c
xx.c: In function `main':
xx.c:10: error: too few arguments to function `exit'
Exit 1
a5:/tmp 106 >

That it does work in Linux is stranger than that it does not work on HP. Compare to the corrected version:

#include
#include

main (int argc, char *argv[])
{
struct in_addr ip;
unsigned long ul;

if (argc != 2) {
printf ("inet_atoh \n");
exit (1);
}

if (inet_aton (argv[1], &ip)) {
printf ("%x\n", ip.s_addr);
ul = ntohl (ip.s_addr);
printf ("%x\n", ul);
}
} /* main */


Enjoy, have FUN! H.Merijn
Enjoy, Have FUN! H.Merijn
A. Clay Stephenson
Acclaimed Contributor
Solution

Re: Memory fault at run time in C program

Yes there is something terribly wrong with your code. It was only working by accident under linux.

main(int argc, char *argv[])
{
struct in_addr *ip;

if (argc!=2)
{ printf("inet_atoh \n");
exit();
}

if (inet_aton(argv[1],ip))
printf("%x\n",ntohl(ip->s_addr));
}

The exit() w/o args is bad but only kills you if argc != 2. Change that to exit(255) or whatever BUT the real problem is:

struct in_addr *ip;
it should be:

struct in_addr ip;

/* This will actually allocate space for the struct rather than simply for a pointer */


Then:

if (inet_aton(argv[1],ip))
printf("%x\n",ntohl(ip->s_addr));

Should be:

if (inet_aton(argv[1],&ip))
printf("%x\n",ntohl(ip.s_addr));
If it ain't broke, I can fix that.
Matias Di Blasi
New Member

Re: Memory fault at run time in C program

Thank for your help. Now it work fine.
Matias Di Blasi