K
Keith Thompson
Myth__Buster said:Yeah, I know, that's the usual pattern - when we allocate a certain
chunk of memory for an object of type T, we would be storing the
respective malloc's return value in an object of type T*. No questions
on that beginner's aspect.
In my question being discussed, we are allocating space for a function
pointer which might *not* be of same size as that of a data pointer on
some machines. No questions on the allocation. It's fine and clear to
me. But, the data pointer(void*) being returned by malloc will be
improper to access the allocated space for the function pointer. And
hence, I would like to see a relevant note under malloc's
documentation.
Of course, I would like to allocate space for a function pointer using
malloc without any dependency on any third-variable such as struct
variable, etc, and use it thereafter(regarding the usage, that will be
another story. I am interested in getting a proper pointer in the
first place from malloc). And yeah, in the realms of C, allocating
space for a function is meaningless as we know sizeof a function makes
no sense.
It *doesn't matter* whether the object being allocated happens to
have the same size as a void*.
Suppose you're allocating a struct object rather than a
pointer-to-function object. Suppose void* is 4 bytes, and your
structure is 1024 bytes. The issues are exactly the same as in the
case you're looking at.
For struct allocation, you need to convert (probably implicitly)
the void* value returned by malloc() to a pointer to the struct.
For pointer-to-function allocation, you need to convert (probably
implicitly) the void* value returned by malloc() to a pointer to
the pointer-to-function.
Pay careful attention to the parallel construction of the two preceding
paragraphs.
I think the fact that the object you're allocating is a pointer is
causing you to confuse the pointer object being allocated with a
pointer *to* that pointer object. They're at two different levels
of indirection, and their relative sizes are not relevant.
You're imagining a special case where there really isn't one.