小雷的学习空间

用硬件包围软件 最终实现软硬通吃

关于“野指针”的问题

最近在用Qt做一个程序,其中就涉及到了“野指针”的,果然出了问题(为什么要用果然呢? 因为以前看过林锐博士的一篇文章提到过这个问题),多次调试检查后才解决。现记录如下:

问题描述:程序的目的大概是一个读文件数据并在QGraphicsScene上画出图形再删掉这些图形。程序每运行一次,虽然调用QGraphicsScene的clear()清除items,但是内存占用增加大概300K左右。

问题分析:程序中有一个循环(大概4000次左右,根据文件大小不同而不同),在循环中我new了一个对象,在循环结束时delete了这个对象。 但是并没有把对象指针赋为NULL,导致每循环一遍产生了一个野指针,从而内存不断增加。以下是程序片段:

while(!in.atEnd())
                        {
                           QPainterPath *pLinePath = new QPainterPath();
                           QVector <QPointF> *plinePoint = new QVector <QPointF>;

                           in>>drawItem;
                           inName>>itemName;

                           L5RoadName.append(itemName);
                           if(drawItem=="LINE" || drawItem=="Line")
                                {
                                   plineNode=2;
                                }
                            else if(drawItem=="PLINE" || drawItem=="Pline")
                                {
                                    in>>plineNode;
                                    in.flush();

                                }
                            else
                                break;

                            for(int i=0; i!=plineNode; i++)
                                {
                                    in>>P1_x>>P1_y;
                                    in.flush();
                                    testPoint.setX(P1_x * 100000000.0);
                                    testPoint.setY(20000000000.0-P1_y * 100000000.0);
                                    plinePoint->append(testPoint);
                                
                                }
                            for(int i=0; i<(plineNode); i++)
                                {
                                    if(0==i)
                                        {
                                            testpoint1=plinePoint->first();
                                            pLinePath->moveTo(testpoint1.x(),testpoint1.y());
                                        }
                                    else
                                        {
                                            testpoint1=plinePoint->at(i);
                                            pLinePath->lineTo(testpoint1.x(),testpoint1.y());
                                        }
                                }

                            L5RoadPath.append( *pLinePath);
                            in>>symbol;
                            delete plinePoint;
                            delete pLinePath;
                            plinePoint=NULL; 
                            pLinePath=NULL; 
                        }

 在增加了最后两条语句后再调试,发现内存占用不再增长。

 

阅读更多
文章标签: delete null 图形 qt xp
个人分类: C++/C#
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭