bug-gplusplus
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

pointer by reference with g++ optimisation


From: passing-by
Subject: pointer by reference with g++ optimisation
Date: 17 Jul 2002 03:47:20 -0700

hi,

could someone explain why I am seeing different results in the code
below
depending on whether the code is compiled with optimisation or not
(the
unoptimized code produces the results i expect).

#include <stdio.h>

void func(void){
    printf("func");
}

void set(void *& ptr){
    ptr = (void*)func;
}

int main (void) {
    void (*fptr)(void) = 0;
    set((void*)fptr);
    fptr();

    return 0;
}

if the above is compiled & run with 'gcc temp.cpp && ./a.out' it
produces
the results I would expect.
if compiled and run with 'gcc -O temp.cpp && ./a.out'  it will result
in a
segfault becuse the fptr remains null.

The same occurs for any pointer type, not only function pointers, and
the
problem disappears if I do a printf("%p", &fptr) in the main. It seems
that optimisation determines that the pointer is not being 'used' and
'optimises out' the setting of the pointer.

My question is, shouldnt this be considered a bug in that it is valid
c++
code and also that the two compilations produce functionally different
code
?

btw: occurs with gcc/g++ 2.95.3 and 3.01, and a workaround is to
declare the
pointer volatile, or stick with trusted pointer to pointer.

apologies if this has been asked before (seems like it must have been)
but I
havent found any related posts.

thx.



reply via email to

[Prev in Thread] Current Thread [Next in Thread]