【发布时间】:2014-05-10 21:56:53
【问题描述】:
这种情况下如何正确释放内存?
我不明白为什么 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会说这样的错误
提前谢谢你!
【问题讨论】:
-
使用 std::vector 自动删除内存并检查缓冲区溢出。
-
您确定“这里的一些代码”不包含一些
continue或break语句吗?我的观点是 - 是否 100% 确定,array_of_numbers_of_circles的 所有 元素都_really_initialized?您也可以使用调试器进行检查。 -
你为什么用
*(matrix + i * 3 + j)而不是更普通更简单的matrix[i * 3 + j]? -
你没有初始化
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 )行中 -
@KirilKirov "some code here"(这里有我刚刚检查的代码。如果是的话:我做 *(array_of_numbers_of_circles + i * 2 + 0) = i + 1; *( array_of_numbers_of_circles + i * 2 + 1) = j + 1;
标签: c++ arrays loops pointers valgrind