مؤشر مشاهدة GDB غير صالح بعد
-
02-10-2019 - |
سؤال
لدي الرمز التالي:
#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 لمشاهدة ذاكرة غير صالحة والتوقف فقط عندما تصبح صالحة؟
ملاحظة: لدي إصدارات GDB 6.0 و 6.3 و 6.4 و 6.6 و 6.8 و 7.0 و 7.1
شكرًا
المحلول 2
لسبب ما ، كنت أستخدم 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)
آمل أن يساعد ذلك على شخص آخر.
ملاحظة: حاولت إضافة هذا كتعليق في المنشور من قبل نيل ، لكن بما أنه لم يتم تنسيقه ، فضلت كتابة إجابة على سؤالي.
نصائح أخرى
ضبط الساعة بعد تخصيص الذاكرة مع 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]
لا تنتمي إلى StackOverflow