Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.c > #103381

Re: Error message for a dangling pointer

From Joe Pfeiffer <pfeiffer@cs.nmsu.edu>
Newsgroups comp.lang.c
Subject Re: Error message for a dangling pointer
Date 2017-02-07 09:49 -0700
Organization A noiseless patient Spider
Message-ID <1btw8654l6.fsf@pfeifferfamily.net> (permalink)
References <dangling-pointers-20170207022252@ram.dialup.fu-berlin.de>

Show all headers | View raw


ram@zedat.fu-berlin.de (Stefan Ram) writes:

>   For teaching purposes, I just wrote this program to show
>   dangling pointers:
>
> #include <stdio.h>
> int main( void )
> { int * p;
>   { int i = 27; p = &i; }
>   printf( "%d\n", *p ); }
>
>   I hope you all agree that »p« in the last line /is/
>   a dangling pointer.
>
>   The error message and output is not what I expected,
>   but still interesting:
>
> main.c: In function 'main':
> main.c:6:3: warning: 'i' is used uninitialized in this function [-Wuninitialized]
>    printf( "%d\n", *p ); }
>    ^
> main.c:5:9: note: 'i' was declared here
>    { int i = 27; p = &i; }
>          ^
> 0
>
>   »i« /was/ initialized in the program,
>   so the error message is not accurate.
>
>   (I do not write »misleading«, since it is so
>   obviously wrong that it won't mislead anyone.)

I get the message in
gcc (Debian 6.2.1-5) 6.2.1 20161124
if I turn optimization -O1 on.  Also, without optimization the output is
27
while with optimization it is
0

I think we can see the code analysis that's leading to the conclusion
that i is being used uninitialized (*p is being replaced by i, which is
not even defined in the scope in which it is being used, let alone
initialized).

Even without the incorrect warning, I have to wonder how useful an
example of a dangling pointer this would be for students.  Since I'd be
*really* surprised to see an actual implementation really allocate a
stack frame for the inner braces, the lecture would go sort of "see?  A
dangling pointer.  And it does exactly the same thing it would have done
if the pointer weren't dangling. That's why we should avoid dangling
pointers" (and of course that's exactly what happens with gcc, without
optimization).  Coax malloc() into reallocating space you can overwrite
the contents or something....

Back to comp.lang.c | Previous | Next — Next in thread | Find similar | Unroll thread


Thread

Re: Error message for a dangling pointer Joe Pfeiffer <pfeiffer@cs.nmsu.edu> - 2017-02-07 09:49 -0700
  Re: Error message for a dangling pointer Manfred <noname@invalid.add> - 2017-02-07 18:42 +0100
    Re: Error message for a dangling pointer Manfred <noname@invalid.add> - 2017-02-07 19:09 +0100
    Re: Error message for a dangling pointer Joe Pfeiffer <pfeiffer@cs.nmsu.edu> - 2017-02-07 21:20 -0700

csiph-web