Could you help me out?

Ross Smith
Sun Oct 31 23:03:00 GMT 1999

Ken Tan wrote:
> The core is dumped when the sentence "sum += *(unsigned int*)(ptr + i) ;" of
> this program is excuting.
> But it is ok when the sentence "sum += *(unsigned int*)(ptr + i / 4 * 4) ;" of
> this program is excuting.
> Is this a bug for g++/gcc version 2.95 / Solaris 7 / SPARC ?
> Or should I use some options in the compiler command line?

Neither. There is a bug in your code.

Standard C and C++ make no guarantee that you can refer to an arbitrary
type through an arbitrary address. If you dereference an int* that does
not actually point to an object that was declared as an int, behaviour
is undefined and anything can happen.

In this case, the Intel CPU happens to allow any block of 4 bytes within
your process's address space to be referred to as though it was an int,
so your program happens (by accident) to work. The Sparc CPU is more
restrictive: it allows this only if the address is suitably aligned (a
multiple of 4), and triggers a bus error if it is not. Even this is only
a property of a particular CPU, and not something required by the
language; a hypothetical system that tagged every address with its data
type and faulted on any improper access (except through char*, which is
a special case) would be consistent with the language standards.

Ross Smith <> The Internet Group, Auckland, New Zealand
  "There are many technical details that make Linux attractive to the
  sort of people to whom technical details are attractive."   -- Suck

More information about the Gcc-bugs mailing list