BCB的TList

    修改了下前人的代码,原本以为这段代码工作得很好的,但是无意间测试了一下,发现程序中出现了内存的泄露。     虽然说内存的泄露占用的空间很小(大概有几十个字节吧),但是心理还是感觉很不爽。     立刻对程序进行检查,模拟错误出现的原因............花费了一个上午的时间,终于把虫子找了出来,可以轻松了一下。         引用一段BCB的Delete方法的注意:      Description Call Delete to remove the item at a specific position from the list. The index is zero-based, so the first item has an Index value of 0, the second item has an Index value of 1, and so on. Calling Delete moves up all items in the Items array that follow the deleted item, and reduces the Count. To remove the reference to an item without deleting the entry from the Items array and changing the Count, set the Items property for Index to NULL. Note:    Delete does not free any memory associated with the item. To free the memory that was used to store a deleted item, set the Capacity property.         可以看出BCB给出的方法并没有自动地帮助我们回收内存空间,而是要求我们必须手动释放内存的空间。     所谓的Delete方法只是删除了对元素的索引,这样就失去对元素控制,严重的时候,不能释放该元素所在空间的内存。         当我们使用Delete方法的时候必须自己释放空间,例如:
typedef struct



{



        int a ;



}kk ;







int main(int argc, char* argv[])



{



        kk *p = NULL ;



        TList *list = NULL ;



        int i = 0 ;



        int size = 10 ;



        list = new TList() ;







        for (i = 0 ; i < size ; i++) {



                p = new kk ;



                p->a = i ;



                list->Add(p) ;



        }



        for (i = 0 ; i < size ; i++) {



                p = (kk *)list->Items[i] ;



                delete p ;



        }







        return 0;



}
这样就不容易发生内存溢出的情况了,对了,还有一点情况,每次Delete方法过后,TList数组的元素数目 都会减少,并且进行重新排列,所以千万注意不要把取得Count的Properties写到for循环中。           
 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值