I\'m having trouble understanding how some pointers work. I always thought that when you created a pointer variable (p), you couldn\'t deference and assign (*p = value) unle
I always thought that when you created a pointer variable (p), you couldn't deference and assign (*p = value) unless you either malloc'd space for it (p = malloc(x)), or set it to the address of another variable (*p = &a)
There are things in C that are disallowed, so the C compiler will issue an error and refuse to compile the program, and there are other things for which the C standard does not define any behavior, so there are no constraints on what an implementation may do ... the reason for this is to give implementations great latitude in how they are implemented and to allow them to produce very fast code. This differs from more modern languages that put a greater value on protecting programmers from their own errors. As a consequence there's a greater burden on the programmer to write valid code.
Your code is an example where the behavior is undefined. The compiler does not generate checks to see whether the value of p is valid when you dereference and assign it ... it may contain junk and the store may be to an arbitrary location in memory, or it may point to inaccessible memory and the store will crash (there are other possibilities since the behavior is undefined, but these are the ones that will occur in common real-world implementations). That your code crashed on one store but not the other is pure happenstance, an artifact of the fine details of the implementation ... a different compiler, a different version of the compiler, a slight change to your source ... any of these things and others could change the results by changing the value that happened to be in p ... some arbitrary value left on the stack, because p is a stack variable (The C language standard does not mandate or even mention a stack, but common real-world implementations allocate auto variables on the stack.)
The bottom line is that your program is, as you know, wrong, even though it was "allowed". As R. Martinho Fernandes said in the comments, you're unlucky that the first store "worked" ... in a commercial product, having something like that "work" would be extremely unfortunate because it can fail at any time, including the worst possible circumstances. The C language does not help you here ... you need to be very disciplined.