分段故障11:GDB原因13

Segmentation fault 11: gdb reason 13

本文关键字:原因 GDB 故障 分段      更新时间:2023-10-16

这是我的代码:

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;
}

有人可以指出我在代码中的错误,说明我为什么要记忆不正确?

如评论中所述,您在此之前使用userInput

long placeArray[userInput +1];

因此,当您在下面的循环中访问它时,placeArray不会像您期望的那样大小。这将导致写入您没有分配的记忆,并且会弄乱您的堆栈。

您的数组分配不正确。

long userInput;
cout << "enter: "; 
cin >> userInput; 
if (userInput <= 0)
{
   cerr << "error" << endl;
   exit(1);
}
long* placeArray = new long[userInput +1]; 
long divisionPlace, modPlace; 
long number = userInput; 
long two = 2; 
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; 
delete [] placeArray;