The post you linked explains it more or less. One thing is doesn't touch on is undefined behavior - which is exactly what will happen in your version without malloc.
All sorts of things can go wrong if you try to use such a pointer - you haven't said where it should point to. It could point literally anywhere.
This line:
int *ptr = malloc(sizeof(int));
is indeed an initialization. What's happening here is two things: (1) malloc is reserving space in memory so that you can subsequently use the pointer and (2) its returning the starting address of that memory.
The address gets assigned to ptr - which is itself a variable. And, like all variables, you can't use them uninitialized. If you do, that's invalid code and therefore, it results in undefined behavior.
Let's drill down this point a little more:
If you don't call malloc, your pointer is invalid and should not be used. To prove this, try compiling your code, say using good old gcc.
If you run:
gcc program.c # no flags
it will compile -- but just because gcc gave you a binary, it doesn't mean it will do what you want. When you run it, it will (most of the time) fail miserably.
However, if you run:
gcc -Wall program.c # enable warnings
it will warn you that ptr is being unused uninitialized. But, it will still produce a binary which you can run - resulting in the same thing as before.
Finally, if you run:
gcc -Wall -Werror program.c # enable warnings and turn them into errors
it will again warn you of the same thing but this time, it won't produce a binary -- and this is what you really want in this situation. Here, gcc is telling you that something is really very wrong and that your code is simply not valid.
Now, back to the point about undefined behavior. Once you've compiled your invalid code (using either of the first two methods - BTW please never do this), running it will often give you a "segmentation fault" (seg fault). However, it doesn't have to and there are no guarantees as to what your program will do. All variables, including pointers, need to be initialized.
BTW, if you look at this post, it tells you why you need to call malloc here at all -- its because you're allocating memory dynamically, so it will be in the heap rather than on the stack.
int *ptr = 1000;Should that be*ptr = 1000;as in first code?int *ptr; *ptr = 1000returns segmentation fault upon printing. When I used malloc, this did not occur and I was able to print the value ptr is pointing to.