Eric Steen
Eric Steen

Reputation: 739

Generic Pointers in C and memory allocation

How does the machine know how much space to allocate for a generic pointer? Is it only allocated when cast to a type?

Upvotes: 0

Views: 1368

Answers (4)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726549

All pointers are of the size known to the compiler at compile time; it is the size of the item being pointed to that may be different. You pass the required size to malloc/calloc yourself, so the compiler has no problem with allocation.

EDIT (in response to a comment) There are cases when sizes of different pointers are different. For example, in the code compiled for Harvard architecture a data pointer must include an extra storage that distinguishes the data stored in program memory from the data stored in the data memory, while function pointers do not need that extra storage. However, this is known to the compiler, so it knows the required allocation size from looking at the type of the pointer.

Upvotes: 1

zellio
zellio

Reputation: 32484

On the majority of platforms pointers are generally of a fixed size based on the memory architecture of the system you are compiling for. Their type, with regard to that, is irrelevant. An int point is the same size as a point to a complex struct. The fact that it's void doesn't change this.

Upvotes: 1

R.. GitHub STOP HELPING ICE
R.. GitHub STOP HELPING ICE

Reputation: 215241

I'm not sure what you mean by a "generic pointer", but if you mean "pointer to void", it's simply a type capable of representing any other pointer value. This does not mean it has to be arbitrarily large; in fact it's (defined to be) the same size and representation as "pointer to character", which can also point to any type.

Upvotes: 3

RoneRackal
RoneRackal

Reputation: 1233

Pointers are all the same size no matter what they are pointing to, it's only the thing they are pointing to that can be different sizes.

Upvotes: 0

Related Questions