Bug 7285 - printing expression gives different result to executing equivalent statement
Summary: printing expression gives different result to executing equivalent statement
Status: ASSIGNED
Alias: None
Product: gdb
Classification: Unclassified
Component: cli (show other bugs)
Version: 6.5
: P3 normal
Target Milestone: ---
Assignee: Not yet assigned to anyone
URL:
Keywords:
Depends on:
Blocks:
 
Reported: 2001-07-24 09:08 UTC by dcoutts
Modified: 2024-01-09 18:50 UTC (History)
2 users (show)

See Also:
Host:
Target:
Build:
Last reconfirmed:


Attachments
gdb_bug.c (100 bytes, application/octet-stream)
, dcoutts
Details

Note You need to log in before you can comment on or make changes to this bug.
Description dcoutts 2001-07-24 16:08:02 UTC
[Converted from Gnats 180]

Printing the value of an expression on the gdb command line
can have a different answer from when the same expression
is evaluated by the machine, even on native targets.

The example I use is long lx = -(1 << 63)

I came across this piece of code when debugging gdb with gdb.
On a 64bit target, this code crops up in get_discrete_bounds
when called with a TYPE_CODE_INT argument:
*lowp = -(1 << (TYPE_LENGTH (type) * TARGET_CHAR_BIT - 1))

As a side issue this code does not have the expected effect 
on a 64bit target, it gives the result 0, which is not the
most negative number avaliable in the representation, (which
was the intent of the code, right?)

Release:
gdb 5.0 (mips-sgi-irix6.5, and others)

Environment:
native mips-sgi-irix6.5x
gdb build both with system cc, and gcc 2.95.3

How-To-Repeat:
when debugging the attached C program, if we print the value
of the expression we get one answer:

(gdb) p (long) -(1 << 63)
$1 = 0

however, executing the statement and checking the result:
6        lx = -(1 << 63);
(gdb) n
(gdb) p lx
$2 = -2147483648

here lx is defined as long, so I would expect that -(1 << 63)
cast to a long would have the same value as assigning the 
same expression to a varialbe of type long.

We get the same behaviour with llx, which is a long long.
On the mips-sgi-irix6.5x target, long is 32bit and long long
is 64bit.
Comment 1 dcoutts 2001-07-24 16:08:02 UTC
Fix:
Don't trust the expression evaluation too much.
Comment 2 Hannes Domani 2024-01-09 18:50:09 UTC
(In reply to dcoutts from comment #0)
> 6        lx = -(1 << 63);
> (gdb) n
> (gdb) p lx
> $2 = -2147483648

Isn't that undefined behavior?

gcc has this warning:
```
gdb_bug.c: In function 'main':
gdb_bug.c:6:12: warning: left shift count >= width of type [-Wshift-count-overflow]
   lx = -(1 << 63);
            ^~
```

And gdb also shows a warning nowadays:
```
(gdb) p (long) -(1 << 63)
warning: left shift count >= width of type
$1 = 0
```