Hi,
I'm learning C++ at the moment using one of Jesse Liberty's books and got to the pointers day.
They ask to code a stray pointer as an exercise and give as a solution the following code:

int main()
{
  int *pVar;
  *pVar = 9;
  return 0;
}

Could anyone tell me why is pVar a stray pointer?

Thanks,

Recommended Answers

All 3 Replies

Because the pointer has not been initialized to anything. It just points to some random location in memory, which your program may, but probably does not, own. Before using a pointer you must initialize it to point somepace. For example:

int *pVar;
int number;
pVar = &number;
*pVar = 9;
commented: beat me to it :P +3

OK, thank you.

Theres also another common mistake that people make, which can easily cause memory leaks, consider this example:

int *varPtr = new int[1000]; // Allocate 1000 int's
int intArray[] = {1, 2, 3, 4, 5}; // Make an array
varPtr = intArray; // Assign varPtr with the adress of intArray

In this example, you allocated 1000 int's, but then you made varPtr (pointing to the 1000 int's) point to intArray instead, so what just happened to those 1000 int's you just allocated? To remove the problem, make sure you call the delete[] operator before reassigning the pointer.

commented: Good one -- I've seen that here too :) +36
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.