🚀 go-pugleaf

RetroBBS NetNews Server

Inspired by RockSolid Light RIP Retro Guy

1 total messages Started by Harald Albrecht Wed, 04 Dec 1996 00:00
-O2 bug (?)
#6117
Author: Harald Albrecht
Date: Wed, 04 Dec 1996 00:00
81 lines
3053 bytes
Well -- some might call it a bug, others might call it a feature.

After recompiling some production code using the -O2 switch with gcc
I've got
SIGSEGVs which disappeared when compiling either without -O or -O2 or
using
HP's own cc compiler (HP-UX 9.0.x). I've tracked down the problem and I
was able
to recreate it using the short code example at the end of the posting.

The basic problem is that someone wanted to use a constant pointer (X *
const p).
As he needed to initialize that pointer within some allocation function,
he simply
casted away (yuk!) the const attribute. Otherwise the compiler wouldn't
allow him
to set (modify) the pointer. When using that pointer he got a NULL
pointer as the compiler
was tought that the pointer was going to be constant. And so the
compiler happily decided
to load the pointer immediatly with its NULL value as this is surely
faster than
fetching the pointer from the stack frame.

Is there any compiler option which makes the compiler either:
  - complain about that dirty cast (like: "it's illegal to cast a
constant pointer to
    a non-constant pointer"),
or
  - make the compiler's optimizer see that dirty cast and let him drop
the const
    attribute from the pointer.

Any comments appreciated.

And here comes the source code:
-------------------------------------------------------------------------------------------
/*
 * Demonstrates a problem with optimization when messing around with
 * the const qualifier and typecasts.
 *
 * Compile the program with -O and gcc will optimize too good (well --
 * gcc is just doing right, it's a dangerous type cast that triggers the
 * problem). Run the program and you should get:
 *   Allocated X at address 0x400031B0
 *   Pointer to X is now 0x00000000
 */
#include <stdio.h>
#include <stdlib.h>

struct X {
  int foo;
}; /* struct X */
typedef struct X X;
typedef X * const ConstPtrToX;

void AllocateX(X **p)
{
  *p = (X *) malloc(sizeof(X));
  printf("Allocated X at address 0x%08X\n", (int) *p);
} /* AllocateX */


void UseX(ConstPtrToX p)
{
  printf("Pointer to X is now 0x%08X\n", (int) p);
} /* UseX */


int main(int argc, char **argv)
{
    X * const p = NULL;

    AllocateX((X **) &p); /* This is BAD, BAD, BAD! */
    UseX(p);
    return 0;
} /* main */

/* End of test.c */
-------------------------------------------------------------------------------------------
Thread Navigation

This is a paginated view of messages in the thread with full content displayed inline.

Messages are displayed in chronological order, with the original post highlighted in green.

Use pagination controls to navigate through all messages in large threads.

Back to All Threads