malloc vs calloc and invalid pointers
Dave Jones
djones at megatest.UUCP
Tue Sep 27 06:14:56 AEST 1988
>From article <13731 at mimsy.UUCP>, by chris at mimsy.UUCP (Chris Torek):
> In article <706.2339B3DF at stjhmc.fidonet.org>
> will.summers at p6.f18.n114.z1.fidonet.org (will summers) writes:
>>This got me thinking about a subtle dpANS wording difference:
>>
>> struct _whatever *pstruct;
>>
>> pstruct = (struct _whatever *) malloc (n * sizeof(struct _whatever));
>>
>>is pstruct[n-1] or pstruct+(n-1) -guaranteed- to be allowed on
>>-all- dpANS conformant installations?
>
> Assuming that malloc did not return NULL, yes.
Another way of stating the question is, "Is sizeof(foo) constrained to
be a multiple of the alignment of foo?"
(I have another question at the bottom of this posting.)
The only copy I have of the proposed ANSII C standard is a pretty early
one. It says, "When applied to a structure or union object, the result
is the total number of bytes in the object considered as a member of an
array..." That indicates that the code above is okay (provided that
your compiler is ANSII C.)
When I wrote a storage allocator a while back, I was not quite willing
to believe the guarantee, so I defined a structure,
"struct heap_unit" which could be redefined on various machines if
necessary. All memory allocations were done in multiples of
sizeof(heap_unit). The first, and so far only, implementation
(for Sun3) was as follows:
typedef struct heap_unit
{ struct heap_unit* next; }
Heap_unit;
The "next" field is used to link free-lists together.
...
Now for the other question: Is it guaranteed that the actual memory
allocated (static, automatic, or malloc) for a variable foo is always
at least sizeof(foo)? It would seem that such should be the case,
but I can't find it stated explicitly in my old draft. (I am completely
uninterested in the moral and socioethical considerations of the following
code.)
bar()
{
char a;
struct something foo;
char z;
a = 'a';
z = 'z';
/* Might the following "step on" char a or char z? */
bzero(&foo, sizeof(foo));
}
Occording to the standard, sizeof(foo) returns the size which would
be allocated for a struct something in an array. Will this much
necessarily be allocated for foo on the stack, insulating it from
char a and char z?
More information about the Comp.lang.c
mailing list