views:

2276

answers:

4
1167      ptr = (void*)getcwd(cwd, MAX_PATH_LENGTH-1);
(gdb) n
1168      if (!ptr) {
(gdb) print ptr
$1 = 0xbff2d96c "/media/MMC-SD/partition1/aaaaaaaaaaa"
(gdb) print &cwd
$2 = (char (*)[3500]) 0xbff2d96c
(gdb) print strlen(cwd)
$3 = 36
(gdb) print "%s",cwd
$4 = "/media/MMC-SD/partition1/aaaaaaaaaaa", '\0' <repeats 912 times>, "��O�001\000\000\000\000��027\000\000\000�3����EL鷠3�000��027\000\000\000\000\000\000\000\027\000\000\000\000��/�027\000\000\000�3����N����\230���鷠3�000��027\000\000\000\000\000\000\000��000\000\000\000\001\000\000\000��M鷠3����\000\000\000\000.\231�027��w\005\b\001\000"...
(gdb) print "%s", ptr
$5 = 0xbff2d96c "/media/MMC-SD/partition1/aaaaaaaaaaa"
(gdb) Quit

Why is ptr printing the string correctly but cwd not; this also affects the program and it crashes if I try to use the cwd...

[edit: turns out that crash was caused by a stupid buffer overflow on this var... grr...not gdb, but the print question was still valid]

+1  A: 

That ptr is displayed as nicely-formatted string and cwd as "byte buffer" is probably specific to gdb. In any case it shouldn't affect your application; according to man 3 getcwd, ptr should point to cwd (or it should be NULL if an error occurred). Can you use ptr without crashing the program?

oliver
A: 

What type is cwd? The above code snippet doesn't tell us that. It could be that ptr being a void* is treated differently by gdb.

Craig H
+1  A: 

The reason that cwd is printed differently in gdb is because gdb knows that ptr is a char * (I guess) and that cwd is an array of length 3500 (as shown in your output). So when printing ptr it prints the pointer value (and as a service also the string it points to) and when printing cwd it prints the whole array.

I don't see any reason why using cwd instead of ptr would lead to problems, but I would need to see some code to be sure.

mweerden
+2  A: 

I agree with mweerden. Trying something I believe is similar to your code, I get:

(gdb) print cwd
$1 = "/media", '\0' <repeats 782 times>, "\016���" ...
(gdb) print (char*) cwd
$2 = 0xbfc8eb84 "/media"

from gdb, so it seems that since cwd was defined as char cwd[3500], gdb prints the entire array, while if you tell gdb to interpret it as a char*, it will work as you expect. If your application crashes, I would assume it is because of something else.

ehdr