Whenever a printf "fixes everything", it's usually because that forces
gcc to put the values on the stack. Without the printf, they're
probably in registers and p points to who knows what.
If you grok assembly, try objdump on the executable to see what's
going on. If you want to multiply the two halves of a long long, I'd
suggest shifting and masking it out explicitly instead of using
pointer tricks like this.
--david
On 3/19/07, Gustavo Rios <[EMAIL PROTECTED]> wrote:
No!
p sizeof is 4 bytes, p is the frst byt of &x, and p + 1 is the 4th
byte. Casting is only on attribution of &x to p.
Realize, p[0] evals to 1 and p[1] evals to 2 as it should be. Only
problem relates to p[0] * p[1]. I believe it should (1 * 2), i.e., 2.
Not a random value.
On 3/19/07, Nick ! <[EMAIL PROTECTED]> wrote:
> On 3/19/07, Gustavo Rios <[EMAIL PROTECTED]> wrote:
> >
> > On 3/19/07, Nick ! <[EMAIL PROTECTED]> wrote:
> > > On 3/19/07, Gustavo Rios <[EMAIL PROTECTED]> wrote:
> > > > I am writing a very simple program but the output change for the c
> > > > variable value change every time i run it. What would it be my mistake
> > > > on the source? Did i forget some thing?
> > > >
> > > > #include <stdio.h>
> > > >
> > > > int
> > > > main(int argc, char **argv)
> > > > {
> > > > unsigned long long x, c;
> > > > unsigned *p;
> > >
> > > ^ this is bad. always say your types in full.
> > >
> > > >
> > > > x = 1, x+= (unsigned long long)1 << 33 ;
> > >
> > > This sets *(&x) to 1, and then sets *(&x) (yes, the same one) to 1+(1<<33)
> > >
> > > > p = (void *)&x;
> > > > c = p[0] * p[1];
> > >
> > > That is, p[1] == *(&x+1) is never getting set to anything. Thus the
> > > reason the output is always changing is because p[1] is always
> > > pointing at a different, random location in memory that has some
> > > previous value.
> > >
> > > Further, p[1] is not your memory, and it's only by chance that you're
> > > not segfaulting.
> > >
> > > > fprintf(stdout, "x:%llu\n", x);
> > > > fprintf(stdout, "0,1:%u,%u\n", p[0], p[1]);
> > > > fprintf(stdout, "c:%llu\n", c);
> > > >
> > > > return 0;
> > > > }
> > > >
> > So, why when i printf p[1], it correctly prints 2?
>
> Uhm. Hmm. Well, x is a long long which is 8 bytes right? A void (when
> doing pointer arithmetic) is taken to only be 1 byte (right?). So p[0]
> is the first byte of those 8, and p[1] is the second, and due to
> coincidence and twos-complement encoding it happens to show you the
> expected numbers. Maybe?
>
> But that doesn't explain why the output is always changing.
>
> Wait, how is * defined on two voids????? That shouldn't even compile
> (unless it's autocasting to int?).
>
> -Nick