Indefinite-length array as member of struct; sizeof(char)

Ray Spalding cc100aa at prism.gatech.EDU
Wed Jul 19 03:57:35 AEST 1989


In article <14474 at dartvax.Dartmouth.EDU> ari at eleazar.dartmouth.edu (Ari Halberstadt) writes:
>I also have a question about memory allocation. Are characters guaranteed
>to be only one memory address long? This is very important in expressions
>such as:
>	nodeptr->string = malloc(strlen(data)+1);
>Should the above line really be written as:
>	nodeptr->string = malloc( (strlen(data)+1) * sizeof(char) );
>I have seen the latter in several books, but it really wasn't clear from the
>examples what should be done.

According to the pANS in K&R II section A7.4.8: "the _sizeof_ operator
yields the number of bytes required to store an object...When _sizeof_ is
applied to a _char_, the result is 1".  And, in B5: "_malloc_ returns a
pointer to space for an object of size _size_" (by which I infer they
mean "size" in the sense of the _sizeof_ operator).

So, either "malloc" above will work (in a correct implementation),
and the choice is a matter of style only.

But, it has nothing to do with the memory addressing scheme of the
machine you're running on; if a byte is not addressable as a unit,
the implementation must allow for that behind the scenes.
-- 
Ray Spalding
Georgia Institute of Technology, Atlanta Georgia, 30332
uucp:     ...!{allegra,amd,hplabs,ut-ngp}!gatech!prism!cc100aa
Internet: cc100aa at prism.gatech.edu



More information about the Comp.lang.c mailing list