I am experimenting with the use of Variable Length Arrays (VLAs) in my C code and trying to iron out my understanding of what they should and shouldn't do.
I have the following snippet from my function:
void get_pdw_frame_usb(pdws_t *pdw_frame, pdw_io_t *pdw_io)
{
...
unsigned char buf[pdw_io->packet_size];
unsigned char *pdw_buf;
memset(buf, '\0', sizeof(buf));
pdw_io is a data structure containing, amongst other things, packet_size, which is of type size_t
the char array buf is to be used to store the contents of a usb bulk transfer packet
I'm trying to instantiate it here as an automatic variable using the C99 VLA approach. I'm then trying to ensure its contents are all zeros.
I'm having a few issues.
Firstly, if pdw_io->packet_size is set to 8 (quite small), then buf is set to a reasonable looking value, i.e. debugging with gdb i can inspect it as follows:
(gdb) p buf
$27 = 0xbffe5be8 "\270", <incomplete sequence \370\267>
If pdw_io->packet_size is set to 12008 (fair bit larger), then I get the following which doesn't look so good:
(gdb) p buf
$29 = 0xbffe2d08 ""
Is 12008 chars too large for a VLA? Or perhaps that gdb output is not something to worry about, it just looks a bit like it hasn't allocated anything to me?
Also when inspecting the size of buf I get the following in both cases:
(gdb) p sizeof(buf)
$30 = 0
which I would have expected to be 8 in the 1st instance and 12008 in the 2nd
Am I wrong in thinking it should be possible to use the sizeof function in this way with a VLA?
My problem is that the subsequent usb bulk transfer is failing and I want to try and rule out the fact it may have something to do with my use of VLAs, which are a bit of a new area for me..
UPDATE
Wrote the following minimal, complete and hopefully verifiable program to try and confirm my observations:
#include <stdio.h>
void test_vla(size_t n)
{
unsigned char buf[n];
printf("sizeof buf = %zu\n", sizeof buf);
}
int main()
{
test_vla(12008);
return 0;
}
now if I break on the printf statement with gdb and run p sizeof buf I get 0 but printf outputs 12008.
gdb version is:
(gdb) show version
GNU gdb (Ubuntu 7.7.1-0ubuntu5~14.04.2) 7.7.1
sizeofon VLAs; newer versions do. See my updated answer.