+ 1

Matrix allocation using double pointer

Hi Please refer below code : I have tried to allocate memory for matrix. Is double pointer only or best suitable approach ? Also I got confused that why 32 + 48 bytes are allocated ? 48 (12 bytes of 4 rows is ok for me to digest) but what about 32 bytes at first line of output? Also is there any memory leak ? I will obviously go for smart pointer and will update code once I am more clear on my doubt of raw pointer implementation. Thanks in advance. https://code.sololearn.com/cjHxkNuLBRXX/?ref=app

20th Nov 2021, 11:43 AM
Ketan Lalcheta
Ketan Lalcheta - avatar
5 odpowiedzi
+ 3
A safe and easy way to implement a matrix in C++, is to use a single `std::vector` as storage, and just provide 2D indexing of that.
20th Nov 2021, 1:34 PM
A S Raghuvanshi
A S Raghuvanshi - avatar
+ 1
Ketan, Isn't the 32 byte allocated for the int*? assuming a 64bit system, a pointer size would be 8 bytes (64 bits), and there you have 4 rows. So we just multiply number of rows (4) by sizeof( int* ) (8) and that's where the 32 bytes was for. Each row has 3 columns, each carries an int (assumed 4 bytes each). And that makes 12 (3 columns * sizeof( int ) (4)). Not sure about memory leaks, but as I remember, each row will need to be freed first, before <ptr> itself was to be freed. Hope I got that right (cmiiw) ...
20th Nov 2021, 12:50 PM
Ipang
+ 1
You're allocating 'r' pointers for the rows of 'c' ints Matrix | V int* R1 -> [M11, M12,..., M1c] int* R2 -> [M21, M22,..., M2c] . . . int* Rr -> [Mr1, Mr2,..., Mrc] Than yes, there is a memory leak as you are only freeing the array of pointers [R1,... Rr] and forgetting about all of the columns [Mxx]
20th Nov 2021, 2:13 PM
Angelo
Angelo - avatar
+ 1
Thanks Ipang , ♨️A.S. Raghuvanshi♨️ and Angelo It is helpful.. I updated code for three different approach. Can anyone help me to solve issue in current code ? Basically I am struggling to have array of pointer with unique pointer.
20th Nov 2021, 5:31 PM
Ketan Lalcheta
Ketan Lalcheta - avatar
0
Ketan Lalcheta The problem is in the declaration of the matrix object. What you want is a unique_ptr that holds an array of unique_ptrs that in turn hold arrays of ints. Not a unique_ptr that holds an array of int pointers. In other words, just replace your declaration of matrix with this unique_ptr<unique_ptr<int[]>[]> matrix(new unique_ptr<int[]>[r]); and it should work.
21st Nov 2021, 5:58 PM
Anthony Maina
Anthony Maina - avatar