I'm kinda newbie in programming, i'm in the part of learning to handle pointers.
I was writing a code to capture an undefined number of user numerical inputs
the code is as follows:
int ct=0,in=0,temp=0;
int *p2in;
p2in =∈
while (1)
{
cout<<"Enter a number (1 to 9) or press 0 to exit: "<<endl;
cin>>temp;
if (temp == 0)
break;
else
{
*p2in = temp;
p2in++;
ct++;
}
}
cout<<"the typed values are: "<<endl;
p2in = ∈
for (int i=0; i<ct-1; i++)
cout<<"Position: "<<i<<" has value: "<<*(p2in+i)<<endl;
the program works fine up until the end of the main (the above) function, where the "stack around variable 'in' was corrupted" appears.
I'm working on Visual Studio 2008 in a C++ Win32 Console Application
I've been reading the forums for this problem, which is not uncommon, but they all seem to deal with fixed size arrays, which in my case don't apply since i don't know in general, how many values the user will type.
Can anyone gimme a hand where is the overflow writing??
Chances are it's just because you are compiling in debug mode, and VC++ will then implement routines for bug and error control. Try switching to release configuration (find the configuration manager on the menus) and then compiling.
You shouldn't just increase the memory address into empty space, as Bazzy noted, that's why you got that error - you were accessing memory that your program did not have.
The solution is usually to just create a new variable. Better to do that than mess around with the way the stack handles your variables.
... instead of increasing the pointer value (the memory address) into empty space, i should create a new variable?...
I knew i was writing out of "in", but since i need an address to go back to once i'm done capturing values, seemed fine to initialize the pointer to a variable and then fill the following memory "addresses" with the incoming data, but given that i don't know how many are coming, how can i create such variables...
sorry, this may seem quite dumb, but i've spent perhaps too much time on this and i'm not seening something really simple...
You can't just reach into the following memory addresses. Think of it this way: the memory there is not available to your program. Accessing it is a no-no. I personally don't even see why you care what the addresses are; it's completely and utterly irrelevant. You'd need to create an array for that.
The real solution is to use std::vector. Every time you get a valid input you push_back it onto the vector. The vector can grow to a (theoretically but not actually) infinite size where as an array's size is set.