#include <stdlib.h>
struct timer_list
{
};
int main(int argc, char *argv[])
{
struct foo *t = (struct foo*) malloc(sizeof(struct timer_list));
free(t);
return 0;
}
Why the above segment of code compiles (in gcc) and works without problem while I have not defined the foo struct?
because in your code snippet above, the compiler doesn’t need to know the size of
struct foo, just the size of a pointer tostruct foo, which is independent of the actual definition of the structure.Now, if you had written:
That would be a different story, since now the compiler needs to know how much memory to allocate.
Additionally, if you at an point you try to access a member of a
struct foo*(or dereference a pointer to a foo):The compiler would also complain, since at this point it needs to know the offset into the structure of
x.As an aside, this property is useful to implement an Opaque Pointer.