Assigning value 20 to next address in the memory using *(p+1) and printing does not produce output

Solution 1:

In the following:

int a=10 ;

When a is declared and initialized, 10 is placed in memory at the location it was created, as indicated in the following depiction of memory:

|?|10|?|...
  ^
  a

Then the statements

int *p;
p = &a;

create a pointer p, the set the pointer to point to the same location

|?|10|?|...
  ^
  p

In the statement *(p+1) = 20;

*(p + 1) references a place in memory that your process does not own, 1 memory location beyond a

    |?|10|?|...
         ^

attempting to assign a value there invokes undefined behavior.

Solution 2:

This actually hits me in a very dubious manner. I get Segmentation fault in the code. We had different results.

Firstly, who gave you any guarantee that p + 1 is even memory? It could very well be 0x00. No joke! You could be on a weird system in which the memory works backwards and if &a is 0x04, then a + 1 would be 0x00. There is no system in which memory is backwards for some reason, but it could happen. I don't think the standard enforces anything related to this(correct me if I'm wrong). This would just create confusion, no wonder nobody has tried this.

Secondly, who gave you any guarantee that p + 1 is not already used? The compiler might be using it, which it does very often.

Thirdly, who gave you any guarantee that picking up some memory that you haven't allocated will even work? Allocating memory is basically reserving memory, if you don't do that nothing is guaranteed to work. Imagine a bus. If you won't reserve a seat, there's no guarantee that you'll be able to sit on it.

So what happens? Undefined behaviour! Basically, if this situation is reached, then the compiler could make code that sends death threats to the president and enrols you for Militia training from a terrorist organisation and the compiler could still call itself "ISO/IEC 9899:2018 compliant". Unless there's an all-catching "compiler can't insert malicious code" phrase in the standard. I haven't checked. Yeah, this is why you should not use obscure compilers. Jokes aside, basically anything could happen, god and only god knows what will happen. Not even the compiler, not you, not ISO know what is going to happen. And that's why "undefined behaviour"s are so dreaded. Don't do weird stuff with memory.

Btw, the thing that makes this especially funny is that &p, with most compilers would be the same as p + 1 on 32 bit systems. And it probably overlap in 64 bit systems. Note the word probably, there's no guarantee.

Solution 3:

Look at it this way, *(p + 1) is the same as having p[1] this means you are looking for a[1] but a is not an array, a[1] does not exist in your program, you can't either read or write in that memory location, we don't really know what's in there, that is why your program suffers from undefined behavior.