[Solved] Segmentation fault when calling a function returning a pointer


Let’s use std::vector:

#include <iostream>
#include <vector>
#include <iomanip>
typedef std::vector<double> DoubleArray;

DoubleArray v_scalar_prod(double a, double *b, int n)
{
   DoubleArray res(n);
   for (int i = 0; i < n; i++) 
   {
        res[i] = a*b[i];
        std::cout << std::setprecision(10) << "res = " << res[i] << '\n';
   }
   return res;
}

int main()
{
   double y[3] = {3., 5.45, 2.};
   DoubleArray z = v_scalar_prod(4., y, 3);
}

No memory leaks, no tracking if delete[] is called, etc. Also, this version can be used in a larger, more complex program without worrying about memory leaks.

The only thing that is up for scrutiny is if b in the v_scalar_prod function is pointing to valid memory before and during the loop. You could also make b a DoubleArray and pass it by const reference. Then you can do the following:

DoubleArray v_scalar_prod(double a, const DoubleArray& b)
{
   DoubleArray res(b.size());
   for (int i = 0; i < b.size(); i++) 
   {
        res[i] = a*b[i];
        std::cout << std::setprecision(10) << "res = " << res[i] << '\n';
   }
   return res;
}

Now you don’t need the n argument, as a vector knows its size by calling vector::size().

1

solved Segmentation fault when calling a function returning a pointer