1

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

4

2 回答 2

0

出于某种原因,我使用的是 gdb-6.3(它在我的 PATH 中,我没有注意到它)。但是,当我尝试使用 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 的帖子中将此作为评论添加,但由于它没有格式化,我更喜欢为我的问题写一个答案。

于 2010-07-08T15:49:14.050 回答
0

在使用 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]
于 2010-07-02T15:07:57.030 回答