Please create an account to participate in the Slashdot moderation system

 



Forgot your password?
typodupeerror
×
Programming

Journal ryanr's Journal: Bug Puzzle #2 4

#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdio.h>

struct
{
  struct in_addr src;
  struct in_addr dest;
} addrs;

int main()
{
  inet_aton ("10.0.0.1", &addrs.src);
  inet_aton ("172.16.0.1", &addrs.dest);

  printf ("src: %s, dest: %s\n", inet_ntoa(addrs.src), inet_ntoa(addrs.dest));
}

[root@scutter root]# gcc bug.c
[root@scutter root]# ./a.out
src: 10.0.0.1, dest: 10.0.0.1

wtf?
This discussion has been archived. No new comments can be posted.

Bug Puzzle #2

Comments Filter:
  • Comment removed based on user account deletion
    • I'll give you a big hint, here's the manpage section for inet_ntoa:

      The inet_ntoa() function converts the Internet host address in given in network byte order to a string in standard numbers-and-dots notation. The string is returned in a statically allocated buffer, which subsequent calls will overwrite.
      • Comment removed based on user account deletion
        • Exactly. C has to finalize the lvals of all the args before it calls the printf function. Since inet_ntoa uses a static buffer, when it returns the address of the buffer that contains the string, it return the same address both time. Whatever one was called last will be the contents of the buffer, and printf just thinks you told it to print the same thing twice.

          I assume the reason the functon works this way is to avoid allocating storage each time (which the programmer would have to remember to free() )

Their idea of an offer you can't refuse is an offer... and you'd better not refuse.

Working...