开发者

gdb watch pointer that is not valid yet

I have the following code:

#include <stdlib.h>
#include &l开发者_如何学Ct;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


Set the watch after the memory has been allocated with 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]


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜