Vladimir Yanakiev
Vladimir Yanakiev

Reputation: 1300

sizeof reference to array in gdb

int main()
{
    typedef unsigned char a4[4];
    a4 p1;
    a4& p2 = p1;
    p2[1]=1;
    cout<<sizeof(p2);
    return p2[1];
}

Compile, start gdb and put breakpoint on return. If you type p sizeof(p2), gdb will print 8 instead of 4 which will be printed if you start the program. If you write in gdb p sizeof(*p2), the output is 4 (the size of array). I think this is because gdb treats p2 as pointer(reference is implemented behind the scene as pointer).

Tested with compilers GCC 4.8.2 and Clang 4.3 on GDB 7.7 linux arch., ubuntu 13.10,

Is this correct or a bug in gdb?

Upvotes: 4

Views: 2216

Answers (1)

Keith Thompson
Keith Thompson

Reputation: 263557

Here's a modified version of your program. I've changed the array size from 4 to 17 to ensure that its size is distinguishable from anything else. I've also changed the type and variable names to make the code easier to follow, and added #include <iostream> so it actually compiles. I've also removed some unnecessary stuff.

#include <iostream>
int main()
{
    typedef unsigned char char17[17];
    char17 arr17;
    char17& arr17_ref = arr17;
    std::cout << "sizeof(arr17) = "
              << sizeof arr17
              << ", sizeof(arr17_ref) = "
              << sizeof(arr17_ref)
              << "\n";
    return 0;
}

When I compile and run it on my system, the output is 17.

When I run it under gdb, I get 8 (the size of a pointer on my system):

$ gdb ./c
GNU gdb (GDB) 7.5-ubuntu
[snip]
Reading symbols from /home/kst/c...done.
(gdb) b 12
Breakpoint 1 at 0x40097e: file c.cpp, line 12.
(gdb) r
Starting program: /home/kst/c 
sizeof(arr17) = 17, sizeof(arr17_ref) = 17

Breakpoint 1, main () at c.cpp:12
12          return 0;
(gdb) p sizeof(arr17)
$1 = 17
(gdb) p sizeof(arr17_ref)
$2 = 8
(gdb) c
Continuing.
[Inferior 1 (process 23420) exited normally]
(gdb) q
$ 

Yes, this is a bug in gdb. gdb is supposed to evaluate expressions as they'd be evaluated in a running program; in this case, it fails to do so.

(I'm using gcc 4.7.2 and gdb 7.5 on Linux Mint 14.)

UPDATE :

The OP submitted a bug report: https://sourceware.org/bugzilla/show_bug.cgi?id=16675 and it's been fixed. The patch was approved and committed 2014-04-14. I still see the bug in gdb 7.7.1, but it's fixed in 7.11.1.

Upvotes: 4

Related Questions