Here is my code:
int main(){
long userInput;
long placeArray[userInput +1];
long divisionPlace, modPlace;
long number = userInput;
long two = 2;
cout << "enter: ";
cin >> userInput;
for (int i = 1; i < userInput; i++) {
divisionPlace = number / two;
modPlace = number % two;
placeArray[number - i ] = modPlace;
}
for (int i = 0; i < userInput; i++) {
cout << placeArray[i] << " ";
}
cout <<endl;
return 0;
}
Can someone point out my error in the code as to why I am mishandling memory?
As was mentioned in a comment, you’re using
userInputbefore it’s initialized here:So
placeArrayis not going to have the size you expect it to when you access it in the loop below. This will lead to writing to memory you didn’t allocate, and will mess up your stack.