Pointer is freed

I do not understand what might be wrong in the following code. It generates a "pointer that was not freed" error.

#include "mpi.h" using namespace std; void changeArray(bool* isPrime){ delete[] isPrime; isPrime = new bool[10]; } int main(int argc, char * argv[]) { int size, rank; MPI_Init(&argc, &argv); MPI_Comm_size(MPI_COMM_WORLD, &size); MPI_Comm_rank(MPI_COMM_WORLD, &rank); bool* isPrime = new bool[1000]; changeArray(isPrime); delete[] isPrime; MPI_Finalize(); return 0; } 

But if I put the function code directly in main, this is normal. If I do not use MPI, this is also normal. What have I done wrong?

+4
source share
1 answer

The problem is that the isPrime pointer that you define outside of changeArray() does not change to changeArray() . Its value is copied to the call, where the array is allocated, but the newly allocated array pointer is stored only in this temporary variable, which is destroyed when the function exits. After the call, the isPrime pointer in main() still points to the same place as before the call, and therefore delete[] in main() tries to free the freed memory.

To verify this, print the value of isPrime before and after calling changeArray() and the value of the newly allocated isPrime inside changeArray() .

The solution is to pass isPrime by reference:

 void changeArray(bool*& isPrime){ delete[] isPrime; isPrime = new bool[10]; } 
+4
source

All Articles