GDB打印char数组中的所有值

时间:2015-04-09 02:31:00

标签: c gdb

我在我的数组中存储了各种文件名,这些文件名由空字节分区。调试时,我只能看到第一个文件名。所以,例如,如果我的数组是这样的:hello.txt00000hello2.txt,我只能看到hello.txt。如何打印整个阵列?我在其他地方找不到这样的命令很困难。

3 个答案:

答案 0 :(得分:14)

您可以使用x/999bc,其中999是数组的大小,例如:

paul@thoth:~/src/sandbox$ gdb ./str
GNU gdb (GDB) 7.4.1-debian
Copyright (C) 2012 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.  Type "show copying"
and "show warranty" for details.
This GDB was configured as "x86_64-linux-gnu".
For bug reporting instructions, please see:
<http://www.gnu.org/software/gdb/bugs/>...
Reading symbols from /home/paul/src/sandbox/str...done.
(gdb) list
1   int main(void) {
2       char * p = "hello\0world\0hahaha";
3       return 0;
4   }
5   
(gdb) b 3
Breakpoint 1 at 0x4004b8: file str.c, line 3.
(gdb) run
Starting program: /home/paul/src/sandbox/str 

Breakpoint 1, main () at str.c:3
3       return 0;
(gdb) print p
$1 = 0x40056c "hello"
(gdb) x/19bc p
0x40056c:   104 'h' 101 'e' 108 'l' 108 'l' 111 'o' 0 '\000'    119 'w' 111 'o'
0x400574:   114 'r' 108 'l' 100 'd' 0 '\000'    104 'h' 97 'a'  104 'h' 97 'a'
0x40057c:   104 'h' 97 'a'  0 '\000'
(gdb) 

答案 1 :(得分:1)

您可以尝试将数组定义为:

char ** array;

array = malloc( NUM_ROWS*sizeof char* );
for( int i =0; i < NUM_ROWS; i++ )
{
    *array[i] = malloc( NUM_COLUMNS )
} 

那么代码可以

memset( array[x], '\0', NUM_COLUMNS );
strncpy(array[x], myString, NUM_COLUMNS-1);

其中myString是要放在该行中的数据 和

for( int i = 0; i < NUM_ROWS; i++ )
{
    if( array[i] )
    { // only enters this code block if something placed in row
        printf( "%s\n", array[x] );
    }
}

然后使用&#39; p array [x]&#39;对于数组中的每一行

答案 2 :(得分:0)

使用gdb,您可以使用以下命令来打印数组的元素:

(gdb) print *array@size

如果我的变量 array char*[]类型,例如下面的

const char *array[] = {"first","second","third"};

然后,我可以使用以下命令显示数组的前2个char*条目:

(gdb) print *array@2
$2 = { 0x..... "first", 0x..... "second"}

使用它来显示程序的参数非常方便:

(gdb) print *argv@argc

还可以使用x/Ns *argv x 命令执行相同的操作,其中 N argc 的整数值(即对于argc = 2,x / 2s * argv)

有关打印命令的全部知识的文档是here

相关问题