Today in the lab project encountered a problem, directly on the code:
voidvibe::init (Mat img) {imgcol=Img.cols; Imgrow=img.rows; //dynamically allocate three-dimensional array, Samples[][][num_samples] The number of times the foreground is continuously detected//Dynamic Assign-i Array. //Sample[img.rows][img.cols][num_samples] is a-B, Array which includes all pixels ' samples.Samples =NewUnsignedChar**[Img.rows]; for(inti =0; i < img.rows; i++) {Samples[i]=NewUchar *[Img.cols]; for(intj =0; J < Img.cols; J + +) { //In an array, a value that is increased beyond num_samples to count the number of times that the pixel point is continuously becoming a foreground;//the ' + 1 ' in ' num_samples + 1 ', it's used to count times of this pixel regarded as foreground pixel.SAMPLES[I][J] =NewUchar[num_samples +1]; for(intK =0; K < Num_samples +1; k++) { //when you create a sample library, all samples are initialized to 0//All Samples init as 0 when Creating Sample Library.SAMPLES[I][J][K] =0; } }} Fgmodel=Mat::zeros (Img.size (), CV_8UC1); }
This code, which I downloaded directly on GitHub, is a vibe background modeling code. The content of the code is an array of samples assigned to each point of the image, which means that each point has a sample set, which is a total of cols*rows*sample_num values, so a three-dimensional array is formed.
The problem appears on the destructor. At first I did not see how the code was written, until there was a test video, because the lens of a wide range of shaking, according to the process of rebuilding the vibe background, there is a lack of memory and crashes the problem.
The first thing to think about is that the dynamically allocated array is not properly deconstructed. Look at the original destructor code:
void ViBe::d eletesamples () { delete samples;} ViBe::~ViBe () { deletesamples ();}
Such a notation does not properly release the requested memory. For specific reasons, I guess it may be that the requested memory is not contiguous, so that only an array of two pointers can be freed up.
The correct approach should be to release in the opposite direction to the application memory, the code is as follows:
void ViBe::d eletesamples () { for (int0, i < Imgrow; i++) { for ( int 0; J < Imgcol; J + +) { delete samples[i][j]; } Delete samples[i]; } Delete[] samples; }
This will not be a memory leak problem!
Application and release of C + + dynamic multidimensional array