Pegboy wrote:
>
> Thanks all.
>
> I've found that I'm simply going to have to allocate them separately, like
> CBFalconer is saying.
>
> To get rid of the warning message, I can change:
> nat->entries = nat + sizeof( NAT_S );
> to:
> nat->entries = (NAT_ENTRY_S *)nat + sizeof( NAT_S );
> but that doesn't solve the problem (app crashing).
That's probably because you've forgotten something
rather important about pointer arithmetic: It is always
done in multiples of the size of the pointed-to object.
So your original `nat + sizeof(NAT_S)' does not point
to a spot `NAT_S' bytes beyond where `nat' itself points,
it points to a spot `NAT_S' *elements* beyond the start.
Since `nat' points to a `NAT_S' object, the sum advances
by `sizeof(NAT_S) * sizeof(NAT_S)' bytes -- which is
probably a little more than you intended, no?
The "correction" has a similar problem. In this case,
`(NAT_ENTRY_S*)nat' points to a `NAT_ENTRY_S' object, and
the arithmetic is done in terms of the size of that object.
The advance is now `sizeof(NAT_ENTRY_S) * sizeof(NAT_S)'
bytes -- again, more than you meant.
The simplest way to write the sum so it advances over
one `NAT_S' instance is `(NAT_ENTRY_S*)(nat + 1)'. Alas,
this can also fail, but for an entirely different reason:
alignment. There are perfectly portable ways to deal with
this problem, but they're surpassingly ugly -- and code
that's hard to read is more likely to be damaged during
maintenance than code that's clear. Unless you are really
allocating a whole lot of these things, to the point where
the per-allocation overhead (typically four to eight bytes)
is the difference betwen success and failure, you'd be well
advised to use separate allocations to hold separate data
types.
--