Konstantin Rasskazov
Konstantin Rasskazov

Reputation: 87

How to free the memory correctly in this case

How to free the memory correctly in this case ?

I don't understand why does VALGRIND writes that I have:

"Conditional jump or move depends on uninitialised value(s) "

This is main function:

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;

and function:

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;

}

what's the problem? I don't understand why does VALGRIND say such errors

Thank you in advance!

Upvotes: 1

Views: 112

Answers (2)

Component 10
Component 10

Reputation: 10507

As the error message kind of suggests, this is probably happening because Valgrind believes you are using values in some way before initializing them. Try using the Valgrind flags to tell you where the source of the uninitialized values are.

In answer to your original question "How to free the memory correctly in this case ?", I would strongly suggest you switch to using std::vector and std::auto_ptr to make your code more reliable and robust.

Upvotes: 1

Steve Jessop
Steve Jessop

Reputation: 279405

First, the warning "Conditional jump or move depends on uninitialised value(s)" is nothing to do with whether you free the memory correctly.

You don't initialize all elements of array_of_numbers_of_circles.

When i == n-1 in the outer loop, the inner loop executes 0 times. Hence elements at indexes 2 * n - 2 and 2 * n - 1 are not initialized. However, they are used back in main, in the line if( *(array_of_numbers_of_circles + i * 2 + j) != 0 )

Depending on what's in //some code here, there may be other elements of the array that are not initialized.

Upvotes: 5

Related Questions