Search code examples
cgdbwatchpoint

gdb watch pointer that is not valid yet


I have the following code:

#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);
}

I wan't to watch for arr[10] and see when that array element is being modified.

How can I do this? gdb says the following:

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

Is there a way to tell gdb to watch an invalid memory and stop only when it becomes valid?

PS: I have gdb versions 6.0, 6.3, 6.4, 6.6, 6.8, 7.0 and 7.1

Thanks


Solution

  • For some reason, I was using gdb-6.3 (it was in my PATH and I didn't notice it). But, when I tried with gdb-7.1 it worked!

    Since gdb 7.0 you can watch memory that isn't yours at the moment.

    With the following source code:

    #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);
    }
    

    You can compile with:

    $ gcc -g -o debug main.c
    

    And then debug with:

    $ 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)
    

    Hope it helps for somebody else.

    NOTE: I tried adding this as a comment in the post by Neil, but as it wasn't formatted, I preferred writing an answer to my question.