[arch-general] gcc: loop do not terminate

goodmenzy at gmail.com goodmenzy at gmail.com
Tue May 14 06:01:51 EDT 2013


On 2013-05-14 05:42:04, Daniel Micay wrote:
> Date: Tue, 14 May 2013 05:42:04 -0400
> From: Daniel Micay <danielmicay at gmail.com>
> To: General Discussion about Arch Linux <arch-general at archlinux.org>
> Subject: Re: [arch-general] gcc: loop do not terminate
> 
> On Tue, May 14, 2013 at 5:02 AM,  <goodmenzy at gmail.com> wrote:
> > On 2013-05-14 04:50:11, Daniel Micay wrote:
> >> Date: Tue, 14 May 2013 04:50:11 -0400
> >> From: Daniel Micay <danielmicay at gmail.com>
> >> To: General Discussion about Arch Linux <arch-general at archlinux.org>
> >> Subject: Re: [arch-general] gcc: loop do not terminate
> >>
> >> On Tue, May 14, 2013 at 3:49 AM,  <goodmenzy at gmail.com> wrote:
> >> >   If this function initArr() is moved to the same cpp file of main(),
> >> >   all optimization level get the same result.
> >>
> >> That's the great thing about undefined behaviour, you never know what
> >> you'll get. It's really not something anyone should be relying on
> >> though.... there's a well defined, valid way of declaring a
> >> flexible-length struct member.
> >
> >    Could you please tell me the "well defined, valid way"?
> 
> The two ways given in my earlier message, either the standard C99
> `foo_t array[];` for the last member or the GNU-ism (non-standard)
> `foo_t array[0]`.
> 
> Using `array[1]` and indexing past the end isn't valid C.

OK, So i suggest the following "standard" way here.
Using ptr instead of array, we lost the chance to 
let compiler help us the check memory accessing violate.
Any comment or curse about the following code ?

struct A
{
        int a;
        int b;
        int c;
};

struct B
{
        int numelem;
        /*
         * Old C trick to define a dynamically sizable array just by allocating
         * sizeof(B) + (numelem-1)*sizeof(A) memory.
         */
        struct A*  item;
};

void testing(void)
{
#define NR_STRUCT_A   (4)
	struct B*  ptr = malloc(sizeof(struct B) + NR_STRUCT_A*sizeof(struct A));

	ptr->numelem = NR_STRUCT_A;
	ptr->item    = (struct A*)(ptr+1);

	ptr->item[0].a = 0;
	ptr->item[1].a = 1;
	ptr->item[2].a = 2;
	ptr->item[3].a = 3;
	ptr->item[4].a = 100;  /* Wrong, violate memory accessing here! */
#undef  NR_STRUCT_A
}



More information about the arch-general mailing list