Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strange parameter passing - is this safe?

I'm working on some legacy code and I ran into something that I'm not sure is safe - in fact I'm pretty sure it's undefined, but I'm not entirely sure why (more or less a bad feeling).

For some reason this code has a class, we'll call it A. Class A has an overloaded pre-increment operator (++) that appears to do some operations on the value of a pointer contained within it (we'll call that pointer B).

I found a function call where the user passes in A, and a de-referenced copy of pointer B while using the pre-increment operator that's been overloaded.

foo(++A, *B);

Since A's pre-increment modifies the value pointed to by B, and B is dereferenced and used as a parameter in the same call... is there a problem or should I just leave it this way?

Sorry if this sounds confusing - the code is way too complex to paste in but I did my best to explain the situation. If needed, I'll make some fake code representing the situation but I'm hoping its clear.

Also, I'm aware that it's bad design for this code to pass in a parameter already contained in A separately, but I wanted to understand if there was an actual problem aside from that.

like image 277
John Humphreys Avatar asked Dec 16 '22 06:12

John Humphreys


2 Answers

The order of evaluation of function arguments is unspecified, so if either operation affects the value of the other, then this is indeed a problem.

(In your code, though, this would somehow require B to be a reference to a member of A. As it's written, one would not suspect that there might be a problem (but you noticed this yourself).)

like image 57
Kerrek SB Avatar answered Dec 31 '22 01:12

Kerrek SB


The value of parameters is computed before entering the function. The order of computation is not specified. So the code you given might produce unexpected results. You can fix it with

++A;
foo(A, *B)

but of course, as you said if B is part of A then only A should be passed.

like image 36
Roman Byshko Avatar answered Dec 31 '22 00:12

Roman Byshko