user4149562
user4149562

Reputation:

Pointer manipulation

char statement[1052]="test", *a=inet_ntoa(iphdr->ip_src);
char c[20]="1";
strcpy(c,a);
char *b=inet_ntoa(iphdr->ip_dst);
snprintf(statement, 1052, "INSERT INTO tblname(ip1,ip2) VALUES ('%s','%s')",c,b);
printf("%s\n,statement); 

This works correctly , but when I try to remove the second and third line, the value of b gets printed in a.

Upvotes: 2

Views: 96

Answers (1)

Graham Borland
Graham Borland

Reputation: 60711

From http://linux.die.net/man/3/inet_ntoa

The inet_ntoa() function converts the Internet host address in, given in network byte order, to a string in IPv4 dotted-decimal notation. The string is returned in a statically allocated buffer, which subsequent calls will overwrite.

The second call to inet_ntoa is overwriting the result of the first one. You need to copy the value out to your own storage each time.

Specifically, in your example, both a and b will end up pointing to the same address, in memory which is owned by the inet_ntoa implementation.

Upvotes: 5

Related Questions