Reputation: 527
How come when I increment a pointer and then dereference it I get a random number?
Here is my code:
#include <iostream>
using namespace std;
int main(){
int reference = 10;
int *health = &reference;
int *health1 = health;
cout << "Health Address: " << health <<
"\nHealth1 Address: " << health1 <<
"\nReference Address: " << &reference << endl;
health1++;
cout << "Health1 value after being incremented then dereferenced: " << *health1 << endl;
}
My output is:
Health Address: 0x7fff5e930a9c
Health1 Address: 0x7fff5e930a9c
Reference Address: 0x7fff5e930a9c.
Health1 value after being incremented then dereferenced: 197262882
I was expecting to get a 0 since the next value of the next memory address would be null, but that is not the case in this situation.
Upvotes: 0
Views: 602
Reputation:
I think your misunderstanding comes from the fact that you expect the pointer to point at the address of the next element of an array:
int myarray[] = { 1, 2, 3, 4, 5 };
int* parray = myarray;
std::cout << *parray << std::endl;
parray++; // increment the pointer, now points at the address of number 2
std::cout << *parray << std::endl;
But since there is no array in your example the incremented pointer points at the next memory block. The size in bytes of the type it points to is added to the pointer. What value lies there is anyone's guess:
int myvalue = 10;
int* mypointer = &myvalue;
mypointer++;
Dereferencing such pointer is undefined behavior. When you exceed the memory allocated to your process you will not get a pointer null value or a dereferenced value of 0
.
Upvotes: 2
Reputation: 158
After you increase the pointer, it points to the memory not allocated and initialized by your program, so it's not null as you expected. Each time you run your program, you may get a random integer.
Upvotes: 3
Reputation: 1
(*health1)++;
you need to dereference the pointer as this would increment the address itself and not the value it is pointing at.
Upvotes: 0
Reputation: 2259
Suppose X
is the value of a pointer T *p;
.
If p
is incremented then, p
will point to address X + sizeof(T)
*p
will then give you the value stored at address X + sizeof(T)
. Now depending upon the validity of address X + sizeof(T)
, you will get the result which can be Undefined Behavior in case X + sizeof(T)
is invalid.
Upvotes: 0
Reputation: 5930
I was expecting to get a 0 since the next spot in memory would be null, but that is not the case in this situation.
Your expectation is wrong. After you have incremented your pointer, it is no longer pointing to the valid memory buffer. Dereferencing it invokes an undefined behavior.
Upvotes: 6