CSP> Behold, a function which returns a pointer:
CSP> int* test()
CSP> {
CSP> int i=5;
CSP> return &i;
CSP> }
CSP> Why do I get a "Suspicious pointer conversion"-warning ?
Whatever tool is issuing the warning is doing an excellent job of
helping you. But the message kind of stinks. I would prefer
something more along the lines of "soon to be out of scope address
being returned". But a misleading warning is still better than no
warning at all!
What is the "lifspan" of 'i'. It's contents are only valid while
'i' exists. It no longer exists then the function returns. So if
anyone tries to dereference the returned pointer, he may get back
the right answer, the wrong answer, or the system may even crash
and burn.
CSP> The functions using this concept seems to work OK.
That's the beauty of "undefined behavior". You can very well get
"correct" results on some platforms. But even on your platform, I
*know* I can make it fail. What's happening is that the address
returned is (or rather was) on the stack. You had no intervening
uses of the stack between the function call and the dereferening
of the returned pointer. If you add some code which "clobbers the
stack", you won't be getting the right answer.
CSP> Should I make them differently.
YES! The lifetime of the variable needs to match the lifetime of the
pointer to the variable. Perhaps making i 'static' would be
appropriate.
---
þ Blue Wave/QWK v2.12 þ
---------------
* Origin: St. Louis Users Group (1:100/4)
|