malloc vs calloc and invalid pointers

Dave Jones djones at megatest.UUCP
Tue Oct 4 10:03:04 AEST 1988


>From article <8593 at smoke.ARPA>, by gwyn at smoke.ARPA (Doug Gwyn ):
> In article <827 at goofy.megatest.UUCP> djones at megatest.UUCP (Dave Jones) writes:
>>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)?
> 
> No, under some circumstances an attempt to access some bytes of the
> virtual object "foo" might fail.  For example, if "foo" is a structure
> with a hole at the end.
> 
>>  /* Might the following "step on" char a or char z? */

   It would have been nice if you quoted the code.
> 
> No, the objects are non-overlapping as a consequence of several
> constraints within the dpANS.


I don't know if I asked the question well enough.

typedef struct
{ long number;
  char ch;
}foo;

My old spec says that "sizeof(foo)" returns a number which will
do for allocation of an array of fooes.  In other words, sizeof(foo)
must be a multiple of the alignment-number for foo.  

Let's assume that our machine requires that longs be aligned on
even word boundaries, and that long is four bytes.  Then sizeof(foo)
will probably be 6, although according to the spec, it could be eight,
or ten or twelve...  The actual memory allocated for each cell in the 
array will be sizeof(foo).

The question is whether or not the compiler is bound by this 
same restriction in allocating static and automatic foos.

Suppose for example you declare the following:

foo bar;
char ch2;

Since the alignment number for a char is likely one, an overeager
compiler might allocate only five bytes for bar, leaving ch2 on
an odd byte boundary.  Now the following code will fail:

{ 
  ch2 = 'z';
  bzero(&bar, sizeof(foo));
  putchar(ch2);
}

I have seen plenty of code like this, and I think I could be
pretty sympathetic with a beginner who fell into the trap. I would
prefer that the spec require that the above code be safe.  Does it?



More information about the Comp.lang.c mailing list