Here is a simple matlab function
function [array] = test(num)
array = 1:num;
for i = 1:10 * num
array(i) = sqrt(double(i)) * num;
end
end
It dynamically increase the size of array. I write this code so that coder cannot guess what size of array will return.
Then I use coder to generate C++ code and use following code to call test(int num, coder::array<int, 2U> &array)
. Guess what, It crashed.
auto array = new coder::array<int, 2U>();
test(100, *array);
delete array;
Let's see what happened inside this function.
void test(int num, coder::array<int, 2U> &array)
{
double d;
long long i;
int i1;
// 'test:2' array = 1:num;
coder::eml_integer_colon_dispatcher(num, array);
// 'test:3' for i = 1:10 * num
i = 10LL * num;
if (i > 2147483647LL) {
i = 2147483647LL;
} else if (i < -2147483648LL) {
i = -2147483648LL;
}
i1 = static_cast<int>(i);
for (int b_i = 0; b_i < i1; b_i++) {
int i2;
// 'test:4' array(i) = sqrt(double(i)) * num;
d = b_i + 1;
coder::b_sqrt(&d);
d = rt_roundd_snf(d * static_cast<double>(num));
if (d < 2.147483648E+9) {
if (d >= -2.147483648E+9) {
i2 = static_cast<int>(d);
} else {
i2 = MIN_int32_T;
}
} else if (d >= 2.147483648E+9) {
i2 = MAX_int32_T;
} else {
i2 = 0;
}
array[b_i] = i2;
}
}
First, it allocate memory is size of num. Then it write data to array. The problem here is that it didn't really check index outbound or not.
The real problem here is that array coder produce unlike stl vector is not memory safe. Coder does not write data before check memory outbound.