如何在這種情況下正確釋放內存?如何在這種情況下正確釋放內存
我不明白爲什麼Valgrind的寫道:我有:
「條件跳轉或移動依賴於未初始化值(S)」
這是主要功能:
int n=0;
cin >> n;
float* matrix;
matrix = new float [ n * 3 ];
for(int i = 0; i < n; i++) {
for(int j = 0; j < 3; j++) {
cin >> *(matrix + i * 3 + j);
}
}
int* array_of_numbers_of_circles = findIntersection(matrix,n);
for(int i = 0; i < n; i++) {
for(int j = 0; j < 2; j++) {
if(*(array_of_numbers_of_circles + i * 2 + j) != 0) { //it writes error in if;
cout << *(array_of_numbers_of_circles + i * 2 + j) << " ";
}
}
if(*(array_of_numbers_of_circles + i * 2 + 0) != 0 &&
*(array_of_numbers_of_circles + i * 2 + 1) != 0) { //it writes error in if here too;
cout << "\n";
}
}
delete[] matrix;
delete[] array_of_numbers_of_circles;
和功能:
int* findIntersection(float matrix[], int n) {
//some variables
int* array_of_numbers_of_circles;
array_of_numbers_of_circles = new int [ n * 2 ];
for(int i = 0; i < n; i++) {
for(int j = i + 1; j < n; j++) {
//some code here
*(array_of_numbers_of_circles + i * 2 + 0) = i + 1;
*(array_of_numbers_of_circles + i * 2 + 1) = j + 1;
}
}
return array_of_numbers_of_circles;
}
有什麼問題?我不明白爲什麼VALGRIND會說這樣的錯誤
先謝謝您了!
使用std :: vector自動刪除內存並檢查緩衝區溢出。 –
你確定,這裏的「一些代碼」不包含一些'continue'或'break'語句嗎?我的觀點是 - 是否100%確定,'array_of_numbers_of_circles'的_all_元素是_really_initialized?你也可以用調試器來檢查它。 –
爲什麼使用'*(矩陣+我* 3 + j)'而不是更常見和簡單的'矩陣[i * 3 + j]'? – HEKTO