Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check out the values of dynamic allocated memory in debugging mode?

i'm using eclipse and netbeans for c, and i'd like to check out the values of variables that are dynamically allocated in the memory when i'm debugging (both in eclipse and netbeans).

for some reason, i can only see the value of the pointer itself, and it's first item.

to illustrate: with this code:

int foo[10];

i can check the value of the entire array later on (when debugging). for example, i can check out the value of foo[7] in the watches window.

but with this code:

int *bar = malloc(10*sizeof(int));

i can only check out where bar is pointing, and the value of bar[0] (but not the other values).

how can i watch all the values of the array?


UPDATE: the issue was solved in both eclipse and netbeans.

in eclipse: right click the desired variable in the Variables window -> select Display As Array -> fill in the start index and the array length.

in netbeans: in the Watches window add a new watch with the following format:

*((bar)+0)@10

where bar should be the pointer name, 0 should be your start index and 10 should be its length

if i may add something personal: this is my first ever message on stackoverflow. i hope you found it useful.

like image 363
dvir Avatar asked Dec 02 '11 15:12

dvir


2 Answers

As you are on a pointer variable, the only knowledge that the debugging tool can infer automatically is that you have an address on an integer value. After that fact you can have theoretically anything behind your integer value, it is not possible for the tool to guess that the pointer is in fact the first element of an integer array.

That said, you can try to add a custom watch expression (at least on Eclipse, i don't know netbeans) which casts your pointer into the integer array. I don't know if you can cast with a precise array length. Something like (int[])bar will certainly work but maybe this form may work either (int[10])bar.

Another solution is looking directly on the memory view at the pointer address, but it is more of a mental sport to convert raw endianness hexadecimal output to integer values...

Now if your pointer is always allocated to a memory block of 10 integers, you should preferably consider to statically allocate it using the array form int bar[10];

like image 144
greydet Avatar answered Sep 23 '22 17:09

greydet


I don't know if it will work in Eclipse or Netbeans, but you could try adding a watch on *(bar + 1) for the second "entry". However you probably can't use bar as an array unless the debugger allows you to typecast it to an array (like (int[])bar, which I have no idea if it will even work in real C).

like image 34
Some programmer dude Avatar answered Sep 21 '22 17:09

Some programmer dude