Consider the following example code:
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int *a = malloc(sizeof *a);
*a = 5;
free(a);
return 0;
}
In this example, I allocate the integer a
on the heap and initialize it to 5. This line specifically
int *a = malloc(sizeof *a);
is what is confusing me (the sizeof *a
part). To me, this looks like I am trying to get the size of the variable before it is even created, but I see this style for initializing pointers is extremely common. When I compile this code with clang, I don't get any errors or warnings. Why does the compiler allow this? As far as I can tell, this is akin to doing something like
int a = a + 1;
without any previous declaration of a
. This produces a warning with clang -Wall main.c
:
main.c:17:13: warning: variable 'a' is uninitialized when used
within its own initialization [-Wuninitialized]
int a = a + 1;
What makes this line different from the pointer declaration with sizeof
?