foo.text[0] Was: Auto variable with sizeof == 0
colin at vu-vlsi.UUCP
colin at vu-vlsi.UUCP
Sat Feb 21 08:47:12 AEST 1987
In article <4157 at utcsri.UUCP> greg at utcsri.UUCP (Gregory Smith) writes:
>In article <626 at vu-vlsi.UUCP> colin at vu-vlsi.UUCP (Colin Kelley) writes:
>>
>>Declare the text field to be char text[1], then use
>>
>> lineptr = malloc(sizeof(LINE)-1+length);
>>
>Well, not quite.... the offset of 'text' within the structure is *not*
>equal to sizeof(LINE)-1, so the above call to malloc is asking for N
>bytes too many, where N is 3 on a vax and 1 on a 68K or PDP-11.
>
> [suggestion to wrap the whole field in a dummy struct]
>
>Alternately, change the declaration to text[4] and the malloc call to
>sizeof(LINE)-4.
For that matter, just use 8, or 16, or 1024! The actual constant should be
#defined of course...
But I contend that it isn't necessary to go to all this work to try to rescue
those 1-3 wasted bytes! Even if the memory is that important to you, malloc()
will probably round the number of bytes up anyway, right? I'm pretty sure that
any implementation of malloc() on machine which requires such padding bytes
will certainly round up to a multiple of this padding size (e.g. malloc() on
a VAX will round the request up to the nearest multiple of N, where N may be
as small as 4, but is likely to be a lot larger).
>>Gnuplot (which we posted a couple weeks ago) uses this technique because it
>>seemed to be the most portable...
>Feel like fixing it?
Now hold on here! You've demonstrated that my program MAY waste several bytes
on its malloc() calls (and I contend that it probably won't). How does this
make it broken? [It may well be broken in some other respect, but that's
another story!]
-Colin Kelley ..{cbmvax,pyrnj,bpa}!vu-vlsi!colin
More information about the Comp.lang.c
mailing list