Reputation: 652
I am getting a segmentation fault error when I try to run my program with arguments. Now I've run it through GDB and found the line in question and it looks like this:
*dstip = (*optarg);
the prototype is:
char *dstip;
and finally it is being called in this line:
char *filter = ("ip dest host %s", dstip);
Now looking back at it I'm not surprised it doesn't work as it looks... wrong frankly, and the problem is solved by removing these lines (and altering the filter text) completely. However, I need the IPv4 address being inputed to show up in the error message filter will be used in, and being useless with pointers and having tried different things back and forth I can't get it right. That is, I only get warning initialization makes pointer from integer
and the like... what to do?
Upvotes: 0
Views: 1072
Reputation: 409442
The statement
*dstip = (*optarg);
doesn't set dstip
to point to optarg
. Instead it sets the first character of what dstip
points to to the same value as the first character that optarg
points to. I.e. it's the same as
dstip[0] = optarg[0];
As dstip
is an uninitialized pointer, you change an unallocated area in memory and that will lead to weird things happening.
Also, the expression
("ip dest host %s", dstip)
doesn't do what you think it does, at least if you think it will return a formatted string. What it really does is using the comma operator, which evaluates the expressions on both sides of the comma, but return only the result of the expression of the right side of the comma.
Upvotes: 5