This is the mail archive of the
gdb@sourceware.org
mailing list for the GDB project.
Re: Printing a 2D array in a C program
- From: Pedro Alves <palves at redhat dot com>
- To: Jan Kratochvil <jan dot kratochvil at redhat dot com>, Neven Sajko <nsajko at gmail dot com>
- Cc: gdb at sourceware dot org
- Date: Fri, 4 Mar 2016 18:24:19 +0000
- Subject: Re: Printing a 2D array in a C program
- Authentication-results: sourceware.org; auth=none
- References: <CAL+bK4NidroyapZhGvtVVsiCbu4=Hz56mF4_oU3iXM-rvqY_xw at mail dot gmail dot com> <20160304144231 dot GA7767 at host1 dot jankratochvil dot net> <CAL+bK4MV9ZLkon2PONYRpF0506P8zE3=Ukm0F1zpVDHd2HpAtw at mail dot gmail dot com> <20160304174859 dot GA15741 at host1 dot jankratochvil dot net>
On 03/04/2016 05:48 PM, Jan Kratochvil wrote:
> The bug with the parameter:
> (gdb) s
> p (m=0x7fffffffd2a0, n=1) at matrix2.c:9
> (gdb) ptype m
> type = int (*)[17]
> (gdb) p m
> $2 = (int (*)[17]) 0x7fffffffd2a0
> (gdb) p *m
> $3 = {-134241616, 32767, -134252848, 32767, -140382932, 32767, 2224, 0, -134252032, 32767, -136422399, 32767, 2224, 0, -140329216,
> 32767, -134252112}
It's a C gotcha, but I don't think it's a bug. Essentially, a parameter
declared as an array is really treated as a pointer parameter.
>From http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1256.pdf:
"
6.7.5.3 Function declarators (including prototypes)
Constraints
(...)
7
A declaration of a parameter as ‘‘array of type’’ shall be adjusted to ‘‘qualified pointer to type’’ (...)
"
So the DWARF describes the type as really what is is. See:
~~~~~~~~~~~~~~~~
$ cat array-param.c
#include <stdlib.h>
#include <stdio.h>
enum
{
sz = 17
};
void
p (int m[sz][sz])
{
printf ("m: sizeof m = %d\n", (int) sizeof (m));
}
void
f (void)
{
int m[sz][sz];
printf ("f: sizeof m = %d\n", (int) sizeof (m));
p (m);
}
int
main ()
{
f ();
return 0;
}
$ gcc -v
gcc version 6.0.0 20160301 (experimental) (GCC)
$ gcc array-param.c -o array-param -Wall -Wextra -O2
array-param.c: In function ‘p’:
array-param.c:12:46: warning: ‘sizeof’ on array function parameter ‘m’ will return size of ‘int (*)[17]’ [-Wsizeof-array-argument]
printf ("m: sizeof m = %d\n", (int) sizeof (m));
^
array-param.c:10:8: note: declared here
p (int m[sz][sz])
^
$ ./array-param
f: sizeof m = 1156
m: sizeof m = 8
~~~~~~~~~~~~~~~~
Thanks,
Pedro Alves