c++ - 在这种情况下如何正确释放内存

标签 c++ arrays loops pointers valgrind

在这种情况下如何正确释放内存?

我不明白为什么 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 - 22 * n - 1 的元素没有被初始化。但是,它们在 main 中使用,在行 if( *(array_of_numbers_of_circles + i * 2 + j) != 0 )

根据 //some code here 中的内容,数组中可能还有其他未初始化的元素。

关于c++ - 在这种情况下如何正确释放内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22763648/

相关文章:

bash - 需要 bash 函数中的循环建议

c++ - 仅在 Qt 5.5 中与 RegisterDeviceNotification 链接错误

c++ - 如何在 C++ 中将输入字符串转换为数组?

javascript - 使用 jQuery 填充对象数组和过滤级联下拉列表

ruby - 在 Ruby 中迭代数组的 "right"方法是什么?

java - 迭代循环至少 1000 次

c++ - 运算符 [] C++ 获取/设置

c++ - qt如何知道按钮被点击了?

c++ - 如何在 C++ 中手动抛出 "overflow exception"?

php - 如何在不使用 foreach 结构的情况下组合数组值和单独的常量?