1 2 3 4 5 6 7 8 9 10
|
Matrix* matrix(double* arr, int nrow, int ncol)
{
Matrix* newobj = (Matrix*)malloc(sizeof(*newobj));
allocateData2DbyMalloc(newobj->element, 1, 1); // allocate space for 1x1 matrix
newobj->type = "vec";
*newobj->element = arr; // Leaks the row you allocated above.
newobj->nRow = nrow; // Pretend the matrix has nrow's instead of the 1 it actually has.
newobj->nColumn = ncol; // pretend it has ncol columns.
return newobj;
}
|
On exit, the matrix has room for 1 row and you've copied the first column from the input parameter arr to the matrix, so the matrix has probably taken ownership of that one row? And not the others?
Line 16: if you're allocating a vector then why even let the user pass a parameter specifying the number of columns?
Line 33 Also leaks memory.
Also, your matrix() functions are very fragile, meaning that there are all sorts of hidden conditions:
Matrix* matrix(double** arr, int nrow, int ncol);
arr must be an array of nrow double ptrs and must be allocated on the heap.
Each item in arr must be an array of ncol doubles allocated on the heap.
The returned Matrix takes ownership of arr and the pointers within it. By "Takes ownership" I mean that when you free the matrix, it will free the memory.
Matrix* matrix(double* arr, int nrow, int ncol);
Leaks memory, takes ownership of arr... I think? Sometimes? Depending on nrow and ncol?
Rather than having different storage policies depending on the function used to create the matrix, you should have one consistent policy. If you want different code for vector vs. a matrix, then create different structures for each.
Also, define your memory management policy and stick to it. If you're passing pointers into or out of a function, then DOCUMENT where they point to and who is responsible for deleting them.