Take care if you think to use FBArrayTempalte as a dynamic array. Here is an example of a memory leaking.

  • Our start length of an array is 3. myArray.SetCount(3)
  • Then we change size to 4. Let’s see what happent inside that function
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
if (pCount > mArrayCount) {
if( pCount ) {
const int lTempNewBlockCount = ( (int) (mArrayCount+pCount + mItemPerBlock - 1 ) / mItemPerBlock );
const int lNewBlockCount = (lTempNewBlockCount > 1 ? lTempNewBlockCount : 1);
const int lOldArraySize = mArrayCount*sizeof(Type);
const int lNewArraySize = lNewBlockCount*mItemPerBlock*sizeof(Type);
if( lNewBlockCount > (int) mBlockCount ) {
mArray = (Type *)FBRealloc( mArray, (size_t) lNewArraySize );
mBlockCount = lNewBlockCount;
}
memset( ((char *)mArray) + lOldArraySize, 0, (size_t) (lNewArraySize-lOldArraySize) );
mArrayCount += pCount;
}
}
else
{
mArrayCount = pCount;
}
  • See, the final length of the array now is 7 ! Ok. Now let’s change a size of our array to 4. In that case we will be in a branch else { mArrayCount = pCount; } which means that we simple cut the length of the array with 3 allocated elements. I’m not sure how it’s controlling internaly on FBFree function that we have in our destructor, but it has a very big possibility of memory leaking.
  • And another dangerous moment. If you call SetCount(4) after you have 3 elements length, function GetCount() returns to you 7 as a result.
FBArrayTemplate
Метки:            

Добавить комментарий

Ваш e-mail не будет опубликован. Обязательные поля помечены *