代码之家  ›  专栏  ›  技术社区  ›  Gaston

尚未生效的gdb监视指针

  •  1
  • Gaston  · 技术社区  · 15 年前

    我有以下代码:

    #include <stdlib.h>
    #include <stdio.h>
    
    #define SIZE 100
    
    int* arr;
    
    main()
    {
        int i;
    
        arr = (int*)malloc(SIZE*sizeof(int));
    
        if (arr == NULL) {
            printf("Could not allocate SIZE(=%d)", SIZE);
        }
    
        for (i=0; i<SIZE; i++) {
            arr[i] = 0;
        }
    
        free(arr);
    }
    

    我不想看 arr[10] 并查看何时修改该数组元素。

    我该怎么做?GDB说:

    $ gcc -g main.c
    $ gdb a.out
    ...
    (gdb) watch arr[10]
    Cannot access memory at address 0x28
    

    有没有办法告诉gdb监视一个无效的内存,只有当它变为有效时才停止?

    PS:我有GDB版本6.0、6.3、6.4、6.6、6.8、7.0和7.1

    谢谢

    2 回复  |  直到 15 年前
        1
  •  0
  •   anon    15 年前

    在内存分配到malloc后设置手表。

    (gdb) b main
    Breakpoint 1 at 0x401321: file w.c, line 9.
    (gdb) run
    Starting program: D:\Users\NeilB/a.exe
    [New thread 432.0x53c]
    
    Breakpoint 1, main () at w.c:9
    9       {
    (gdb)
    (gdb) n
    12          arr = (int*)malloc(SIZE*sizeof(int));
    (gdb) n
    14          if (arr == NULL) {
    (gdb) watch arr[10]
    Hardware watchpoint 2: arr[10]
    
        2
  •  0
  •   Gaston    15 年前

    出于某种原因,我使用了gdb-6.3(它在我的路径中,我没有注意到)。但是,当我尝试GDB-7.1时,它起作用了!

    既然gdb 7.0,你就可以看到现在不是你的内存。

    使用以下源代码:

    #include <stdlib.h>
    #include <stdio.h>
    
    #define SIZE 100
    
    int* arr;
    
    main()
    {
        int i;
    
        arr = (int*)malloc(SIZE*sizeof(int));
    
        if (arr == NULL) {
            printf("Could not allocate SIZE(=%d)", SIZE);
        }
    
        for (i=0; i<SIZE; i++) {
            arr[i] = i; /* So it changes from malloc */
        }
    
        free(arr);
    }
    

    编译时可以使用:

    $ gcc -g -o debug main.c
    

    然后调试:

    $ gdb debug
    GNU gdb (GDB) 7.1
    ...
    (gdb) watch arr[10]
    Watchpoint 1: arr[10]
    (gdb) run
    Starting program: /remote/cats/gastonj/sandbox/debug/debug
    Hardware watchpoint 1: arr[10]
    
    Old value = <unreadable>
    New value = 0
    main () at main.c:14
    14          if (arr == NULL) {
    (gdb) cont
    Continuing.
    Hardware watchpoint 1: arr[10]
    
    Old value = 0
    New value = 10
    main () at main.c:18
    18          for (i=0; i<SIZE; i++) {
    (gdb) cont
    Continuing.
    
    Program exited with code 01.
    (gdb)
    

    希望对别人有帮助。

    注意:我试着在Neil的文章中添加这个评论,但是由于它没有格式化,我更喜欢为我的问题写一个答案。

    推荐文章