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

Kon*_*zov 1 c++ arrays valgrind pointers loops

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

我不明白为什么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;
Run Code Online (Sandbox Code Playgroud)

和功能:

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;

}
Run Code Online (Sandbox Code Playgroud)

有什么问题?我不明白为什么VALGRIND会说出这样的错误

先感谢您!

Ste*_*sop 5

首先,警告"条件跳转或移动取决于未初始化的值"与是否正确释放内存无关.

您没有初始化所有元素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,可能还有其他未初始化的元素.