分段错误11:gdb原因13

时间:2012-10-22 19:13:10

标签: c++ memory

这是我的代码:

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

有人可以在代码中指出我错误处理内存的错误吗?

2 个答案:

答案 0 :(得分:3)

正如评论中所提到的,您在此处初始化之前使用的是userInput

long placeArray[userInput +1];

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

答案 1 :(得分:1)

您的数组分配不正确。

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;