The fact that the result is what you expect doesn't mean the code is correct, your program is ill-formed, in int *b = 5
, you are assigning the value of 5 to a pointer, this will be interpreted as a memory address, that's what pointers are used for, so you can use that memory address to access the data, and, for instance, pass it as a function argument so that the data can be manipulated.
If you want to just store an int
you would use an int
variable, so, whilst not illegal, it doesn't make much sense, and deferencing the pointer will invoke undefined behavior, so you can't really use it as a pointer, which is what it is.
You use malloc
so that your program and that specific pointer can be given(assigned) by the system a workable memory address where you can store data for later use, (5
is almost certainly not that).
printf("%d\n", b)
is also incorrect, the specifier to print a pointer value i.e. a memory address is %p
, that is definitely undefined behavior, the correct expression would be:
printf("%p\n", (void*)b);
C gives the programmer leeway to do things that other programming languages don't allow, that is an advantage, but it can also be a problem, programs that compile and seem to run properly may be problematic. When an ill-formed program complies and runs its behavior falls in the category of undefined behavior.
This is defined in the standard and gives the compilers discretionary power to treat the code in any way it sees fit, that includes producing a seemimgly correct result, the problem is that this may work today, and crash tomorrow or vice-versa, it is completely unreliable.