简体   繁体   中英

Using struct pointers in C even if they are not declared

#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 to struct foo , which is independent of the actual definition of the structure.

Now, if you had written:

struct foo *t = malloc(sizeof(struct foo));

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):

((struct foo*)t)->x = 3;

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 .

"And what about free(t)? Can the compiler free the memory without knowing the real size of the struct?" No, compiler doesn't free anything. Free() is just a function with input parameter void *.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM