5

The following small program compiles on gcc and runs fine:

#include <stdio.h>
#include <stdlib.h>

typedef struct foo dne;

int main(int argc, char *argv[]) {
    dne *dne_var = malloc(sizeof(void*));
    printf("%p\n", dne_var);
    return 0;
}

Why is the typedef valid?

Chaosed0
  • 949
  • 1
  • 10
  • 20
  • 11
    You're allocating enough space for a pointer, not a `dne`. – chris Aug 21 '14 at 17:31
  • 7
    As soon as you said `struct foo` you created the type. It's an incomplete type, but it exists. –  Aug 21 '14 at 17:35
  • Interesting - I guess this has nothing to do specifically with the `typedef`. If I remove it and replace instances of `dne` with `struct foo`, it still compiles. I guess it's more the implicit declaration I was confused about. – Chaosed0 Aug 21 '14 at 17:40
  • `dne *dne_var = malloc(sizeof(dne*));` should have been `dne *dne_var = malloc(sizeof *dne_var);`. Then an error would occur. – chux - Reinstate Monica Aug 21 '14 at 18:36
  • Oh, I don't know how I didn't catch that I was doing the wrong thing with that malloc. It wasn't the point of confusion anyway, so I'll change it to make the question more pointed. – Chaosed0 Aug 21 '14 at 18:46
  • 2
    Another incomplete type you might be more familiar with is `void` ; you can't have `void x;`, but you can have pointers to void. However, `void` cannot be completed whereas an incomplete struct type can later be completed. – M.M Aug 21 '14 at 19:36
  • Always [cast the data pointer to void *](http://stackoverflow.com/questions/26751722/usage-of-void-pointers-across-different-platforms/26751747#26751747) before printing using `%p` – Mohit Jain Nov 25 '14 at 04:45

1 Answers1

10

The line

typedef struct foo dne;

implicitly declares an (incomplete at this point) structure struct foo. A pointer to an incomplete type is a complete type, so e.g. it’s size is known and you can declare an object of that type. However, struct foo itself isn’t complete until you provide a full declaration of it, so e.g.

dne dne_var;

or dereferencing your pointer to access the fields of the structure would be invalid.

mafso
  • 5,433
  • 2
  • 19
  • 40