I am trying to explore pointers more,below is one sample piece of code i am trying
This works:
int *arth, art;
art = 100;
arth = &art;
printf("arth address is %p arth+1 value is %d", arth, *(arth + 1));
now if i try to add a large number to arth,i get read access violation
This doesn't:
printf("arth address is %p arth+1 value is %d", arth, *(arth + 1000));
Error:
Exception thrown: read access violation. arth was 0xC9C5EFF964. occurred
ASK:
can some one explain why this works when adding 1 and not when adding 1000
arth
is pointing to a single instance of anint
. Adding any non-zero value toarth
and subsequently dereferencing that new pointer value reads a memory location outside the bounds of the originalint
. This invokes undefined behavior.With undefined behavior, anything can happen. Your program may crash, it may output strange results, or it may appear to work properly. The fact that you didn't crash on the
*(arth + 1))
case but did crash on the*(arth + 1000))
is an example of that.Just because the program didn't crash doesn't mean it didn't do something wrong.