int *i;
*i=123;
Yes. There is no allocated memory to place the value 123
.
Like initializing a variable like int
is not guaranteed to be 0
, an int*
isn't guaranteed to be a safe address.
It also could potentially lead to data corruption.
It can, but there again it could do anything - it exhibits what the C Standard calls "undefined behaviour".
int *i;
This allocates a memory for pointer but this variable is not initialized so it's value is totally random. Then you dereference it so you have a random address and perform a write to this place in the memory but 1) you don't know where the place is 2) this place probably is not yours. You can fix it with initialization like int * i = ( int* ) malloc( sizeof(int) )
Rough odds on a 32-bit operating system:
- Odds to trigger a hardware exception: 99.9995%
- Odds to corrupt program state: 0.0005%
- Odds to accidentally hit the right memory location: 1 in 2 billion
Estimates only to demonstrate orders of magnitude. Relevant only for a Release build. If it does corrupt program state then the odds it will do so consistently climb to close to 100%. A good compiler makes the hardware exception odds 100% in the Debug build. Get a good compiler.
Yes, the code you posted can cause a segmentation fault. You've got a pointer which is uninitialized (doesn't point to any known location) and you then use it to store something. Where does the 'something' go? Good question, to which there is no consistent answer.
You need to initialize that pointer. For example:
int target = 0;
int *i = ⌖
printf("target=%d\n", target);
*i=123;
printf("target=%d\n", target);
I hope this helps.