www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Passing a pointer to a function (by value) changes the pointer value

reply Stefanos Baziotis <sdi1600105 di.uoa.gr> writes:
Hello everyone,

I have a function:
void foo(T *t) { ... }

void bar(...) {
     T *t = ...;
     foo(t);
}

In the debugger, before calling 'foo', 't' had a value (an 
address) let's say 10. Stepping
into 'foo', the 't' that 'foo' got, which is supposed to have the 
same value that the 't' in 'bar' had, actually had a completely 
different value. That caused a very bad bug...

I thought that D behaves in that kind of situations as C/C++, and 
so I thought 'foo' should get the same value but that was not 
true. Needless to say it took a lot of time to notice it
as I would never expect it and I still don't know how to fix it.
How does this happen? Is there are some specifics about pointers 
and / or passing arguments that I should know?

What is also puzzling is that the project is about 4500 lines of 
D code _full_ of pointers
and this happens in all calls I have checked and _somehow_ it was 
working up until now.

Best regards,
Stefanos Baziotis
Apr 28 2019
parent reply Adam D. Ruppe <destructionator gmail.com> writes:
On Sunday, 28 April 2019 at 18:16:24 UTC, Stefanos Baziotis wrote:
 In the debugger, before calling 'foo', 't' had a value (an 
 address) let's say 10. Stepping
 into 'foo', the 't' that 'foo' got, which is supposed to have 
 the same value that the 't' in 'bar' had, actually had a 
 completely different value. That caused a very bad bug...
Sounds like you have a stack corruption bug somewhere else... memory being overwritten by something else. Can you post any more of the context code?
Apr 28 2019
parent Stefanos Baziotis <sdi1600105 di.uoa.gr> writes:
On Sunday, 28 April 2019 at 18:48:55 UTC, Adam D. Ruppe wrote:
 Sounds like you have a stack corruption bug somewhere else... 
 memory being overwritten by something else.

 Can you post any more of the context code?
I fixed it, there was a bug, but not related to stack. Not related to memory at all. As I was trying to fix the bug, the code changed unfortunately and now I try to reproduce the bug but I can't. I use visual D and one interesting point is that one file of the project was not added, but the compiler didn't yield an error although it tried to use its functions (but actually couldn't, I don't know how that can happen too. Using dmd from terminal, that never happens). I think that by adding the file, the changing of pointer value disappeared, but it could also be that in the process, I fixed a memory bug that I didn't notice (although that is quite unlikely). If I can reproduce it, I'll post it. Thanks anyway, - Stefanos
Apr 28 2019