I am working on a code where an array is passed to a function by passing the pointer to the first location. In the function, part of the array is used. This creates an unsafe situation because there is a chance if the caller function does not guess the max size of the array correctly the callee function can write past the array size and a stack overflow can occur. I was thinking of a solution to this and thought of using a function template and passing the array as reference as shown in this example.
modifyArray.h
#define MAXSIZE 10
class modifyArray
{
public:
void create();
void unsafeFunction(double*);
template<int N>
void safeFunction(double (&array)[N] );
private:
int computeLength();
};
modifyArray.cpp
#include <iostream>
#include "modifyArray.h"
int modifyArray::computeLength()
{
return 11;
}
void modifyArray::create()
{
double testarray[MAXSIZE];
unsafeFunction(testarray);
safeFunction(testarray);
}
void modifyArray::unsafeFunction(double* array)
{
int operatingSize = computeLength();
for(int i = 0; i < operatingSize; i++) {
array[i] = i*i;
}
}
template<int N>
void modifyArray::safeFunction(double (&array)[N] )
{
int operatingSize = computeLength();
std::cout<< "Max size" << N <<std::endl;
if(operatingSize > N) return; // Return or raise an exception
for(int i = 0; i < operatingSize; i++) {
array[i] = i*i;
}
}
main.cpp
#include "modifyArray.h"
int main(int argc, const char * argv[]) {
modifyArray C;
C.create();
return 0;
}
I am looking for a solution that is minimally invasive to the existing code. Here I just have to add a template statement, change the argument from double* to reference, and insert an if statement to check the size. I don’t want to do a major rewrite. Also I don’t want to use dynamic allocation, vector, or std::array mostly because of the performance reasons. This is a low level function in a numerical simulation code and performance is very important. Is there a better solution? Is there a pitfall to doing what I am doing?
std::arrayit just a wrapper for an array and has the same run-time performance as a raw array.std::array. The performance will be the same.std::arrayalleviates all of the issues you stated in your post. Astd::arrayknows its own size, so you don't need to pass another parameter denoting this information, and as others stated, astd::arrayis an array, just with member functions. So there is no degradation in performance.std::vector. They are a lot easier than arrays. With arrays, you will need to pass the array, the capacity and optionally the number of occupied elements. The capacity of an array is lost when it is passed to a function.