[comp.std.c] Another malloc question

rhg@cpsolv.UUCP (Richard H. Gumpertz) (10/24/89)

Another question about malloc:

Suppose a system has one data type that must be aligned on a 32-byte boundary
but all other objects can be aligned on a 2-byte boundary.  Suppose further
that the one data type having 32-byte alignment requirements has size X.
Clearly no call to malloc requesting fewer than X bytes can really need 32-byte
alignment; if there wre need of a 32-byte alignment then the size would have
to be at least X.

The current standard seems to prohibit malloc from special-casing requests
for less than size X and returning only even alignment.  Is this overkill in
the language of the standard?  Wouldn't it be better for the standard to only
require malloc(N) to align the return value sufficiently for all objects
of size <= N?  This might let small requests pack more efficiently without
breaking any programs.
-- 
==========================================================================
| Richard H. Gumpertz   rhg@cpsolv.UUCP -or- ...!uunet!amgraf!cpsolv!rhg |
| Computer Problem Solving, 8905 Mohawk Lane, Leawood, Kansas 66206-1749 |
==========================================================================

gwyn@smoke.BRL.MIL (Doug Gwyn) (10/25/89)

In article <428@cpsolv.UUCP> rhg@cpsolv.uucp (Richard H. Gumpertz) writes:
>The current standard seems to prohibit malloc from special-casing requests
>for less than size X and returning only even alignment.

Right.

>Is this overkill in the language of the standard?

No, "simplicity" would be a better word.

Nobody thought there would be sufficient gain in the real world
(as opposed to your hypothetical 32-byte aligned machine) to be
worth the added complexity.

chip@ateng.com (Chip Salzenberg) (10/26/89)

According to rhg@cpsolv.UUCP (Richard H. Gumpertz):
>Suppose a system has one data type "X" that must be aligned on a 32-byte
>boundary, but all other objects can be aligned on a 2-byte boundary.
>The current standard seems to prohibit malloc from special-casing requests
>for less than size X and returning only even alignment.

This feature serves a useful purpose.  Suppose you have pointers to large
structures, and you need more than one special pointer value.  NULL isn't
enough.  You can get a properly aligned structure pointer by calling
malloc(1); use this pointer as the magic cookie.  You can't dereference such
a pointer, but you can assign it and compare against it.

Such a ploy can save you some memory, since you don't have to declare a
static structure just to use its unique address as a magic cookie.

[I hope that this strategy doesn't run afoul some obscure restriction...]
-- 
You may redistribute this article only to those who may freely do likewise.
Chip Salzenberg at A T Engineering;  <chip@ateng.com> or <uunet!ateng!chip>
"'Why do we post to Usenet?'  Naturally, the answer is, 'To get a response.'"
                        -- Brad "Flame Me" Templeton