Search code examples
fortrangdbgfortran

How to print allocatable fortran int64 array in GDB


I know I can print the n+1-th element of a normal integer array data in GDB as

print *((integer *)data + n)

But how can I correctly print the element out if data is an integer(INT64) allocatable array?


Solution

  • Note: some older GDB versions or branches used in some unfortunate OSs or distributions may fail to support the allocatable arrays correctly. In that case use the C syntax.

    If int64_t isn't recognized by an old GDB, use long or whatever old C type corresponds to a 64-bit integer.


    You can really just do

     print data(n+1)
    

    Using

     print *((integer *)data + n)
    

    is C mode GDB syntax, but in Fortran mode it is really simple.

    If you really want the complicated C syntax, you can use it even in Fortran mode, it is

     print *((int64_t *)(&data) + n)
    

    In C mode (after set langauge c), you can also use

    print *((int64_t *)data + n)
    

    this one does not work in Fortran mode (Cannot access memory at address 0x29).


    Example:

    use iso_fortran_env
    
    integer(int64), allocatable :: data(:)
    
    integer :: n
    
    data = [(i, i=1, 100)]
    
    n = 5
    
    continue
    
    end
    

    gdb:

    GNU gdb (GDB; openSUSE Leap 15.1) 8.3.1
    ...
    (gdb) break int64.f90:9
    Breakpoint 1 at 0x4005ec: file int64.f90, line 9.
    (gdb) run
    Starting program: /home/lada/f/testy/stackoverflow/a.out 
    
    Breakpoint 1, MAIN__ () at int64.f90:9
    9       n = 5
    Missing separate debuginfos, use: zypper install libgcc_s1-gcc10-debuginfo-10.1.1+git68-lp151.27.1.x86_64 libquadmath0-gcc10-debuginfo-10.1.1+git68-lp151.27.1.x86_64
    (gdb) step
    13      end
    (gdb) print data(n+1)
    $1 = 6
    (gdb) print *((int64_t *)(&data) + n)
    $2 = 6
    (gdb) set language c
    Warning: the current language does not match this frame.
    (gdb) print *((int64_t *)data + n)
    $3 = 6
    (gdb) print *((long *)data + n)
    $4 = 6