Page 1 of 1
Why *((type **)&p) = new_pointer is better?
Posted: Tue Jan 10, 2012 10:59 pm
by harvey
Hi,
I'm reading kernel codes and saw some strange assigning statements like:
int *p = NULL, n = xxx;
*((int **)&p) = &n;
Why not to directly assign like
p = &n;
Is there any special reason for this?
Re: Why *((type **)&p) = new_pointer is better?
Posted: Tue Jan 10, 2012 11:34 pm
by NickJohnson
Perhaps this is an attempt to force p to not be optimized out of the stack frame or to force a write to memory. It's particularly odd that &p is being cast to int**, considering that it already is that type. I'm assuming you found this in Linux: where did you find it? It may be part of a more elaborate hack.
Re: Why *((type **)&p) = new_pointer is better?
Posted: Tue Jan 10, 2012 11:39 pm
by harvey
NickJohnson wrote:Perhaps this is an attempt to force p to not be optimized out of the stack frame or to force a write to memory. It's particularly odd that &p is being cast to int**, considering that it already is that type. I'm assuming you found this in Linux: where did you find it? It may be part of a more elaborate hack.
I saw this somewhere in Linux kernel some time ago and I can't remember exactly where it is. I need some time to search:-)
Re: Why *((type **)&p) = new_pointer is better?
Posted: Wed Jan 11, 2012 12:20 am
by Jezze
Perhaps just a very bad programmer? =)
Re: Why *((type **)&p) = new_pointer is better?
Posted: Wed Jan 11, 2012 2:03 am
by Solar
Jezze wrote:Perhaps just a very bad programmer? =)
A possibility never to be ruled out easily.
Re: Why *((type **)&p) = new_pointer is better?
Posted: Wed Jan 11, 2012 2:36 am
by harvey
berkus wrote:You might be reading it wrong.
Maybe...
I'll let you know if I find the place.
Re: Why *((type **)&p) = new_pointer is better?
Posted: Wed Jan 11, 2012 4:14 am
by AJ
Hi,
Jezze wrote:Perhaps just a very bad programmer? =)
For me, declarations like:
always ring alarm bells anyway, even if, as in your example above, it was intended that n is not a pointer.
Cheers,
Adam
Re: Why *((type **)&p) = new_pointer is better?
Posted: Wed Jan 11, 2012 4:27 am
by harvey
AJ wrote:Hi,
Jezze wrote:Perhaps just a very bad programmer? =)
For me, declarations like:
always ring alarm bells anyway, even if, as in your example above, it was intended that n is not a pointer.
Cheers,
Adam
yes, n is a int, so I added & and the focus is actually on the second statement.
Re: Why *((type **)&p) = new_pointer is better?
Posted: Wed Jan 11, 2012 4:32 am
by AJ
Hi,
AJ wrote:even if, as in your example above, it was intended that n is not a pointer.
I'm not saying your example got it wrong. It may just be a matter of preference, but I was just saying that declaring a type and a pointer to that type in the same statement is not always the clearest way of doing it.
Cheers,
Adam