我正在尝试根据输入数据的动态大小动态重新分配mex中的某些数组。
std::vector<mxArray*> arrays;
size_t row_size = 1;
for(size_t i = 0; i < col_count; ++i) {
mxArray* output = mxCreateNumericMatrix(row_size, 1, mxDOUBLE_CLASS, mxREAL);
arrays.push_back(output);
}
void grow() {
size_t new_size = row_size * 2;
for(size_t i = 0; i < col_count; ++i)
mxSetM(arrays[i], new_size);
row_size = new_size;
}
size_t current_row = 0;
while(...) {
if(current_row >= row_size)
grow();
//do some assignment to the arrays
double* p = mxGetPr(arrays[col]);
p[current_row] = value;
++current_row;
}
这种情况有一段时间了,但我显然会以某种方式破坏记忆,因为它会随机炸弹:
MATLAB: double free or corruption (out): 0x00007f9714314f50 ***
如果我预先分配“矩阵”(永远不会调用grow
),一切都会毫无问题地运行。