在这种情况下如何正确释放内存?
我不明白为什么 VALGRIND 会写我有:
“条件跳跃或移动取决于未初始化的值”
这是主要功能:
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会说这样的错误
提前致谢!
最佳答案
首先,警告“Conditional jump or move depends on uninitialised value(s)”与你是否正确释放内存无关。
您没有初始化 array_of_numbers_of_circles
的所有元素。
当外层循环i == n-1
时,内层循环执行0次。因此索引 2 * n - 2
和 2 * n - 1
的元素没有被初始化。但是,它们在 main
中使用,在行 if( *(array_of_numbers_of_circles + i * 2 + j) != 0 )
根据 //some code here
中的内容,数组中可能还有其他未初始化的元素。
关于c++ - 在这种情况下如何正确释放内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22763648/