码迷,mamicode.com
首页 > 其他好文 > 详细

写了一个bug----使用已经被删除的内存

时间:2018-06-11 01:59:43      阅读:159      评论:0      收藏:0      [点我收藏+]

标签:let   stream   ext   pac   memory   i++   ret   space   int   

#include <iostream>
#include <stdio.h>
#include <memory.h>

using namespace std;
const int NN = 5;
class Piece
{
    private:
        int r;
        int c;
        int** p;
    public:
        Piece()
                : r(0), c(0)
        {
            p = nullptr;
        }
        Piece(int r, int c, int (*pp)[NN])
        {
            this->r = r;
            this->c = c;
            this->p = new int*[r];

            for(int i = 0; i < r; i++)
            {
                this->p[i] = new int[c];
                memcpy(this->p[i], pp[i], c * sizeof(int));
            }
        }
        ~Piece()
        {
            cout<<"delete"<<endl;
            for(int i = 0; i < r; i++)
                delete[] p[i];
            delete this->p;
        }
        int getR()
        {
            return this->r;
        }
        int getC()
        {
            return this->c;
        }
        int ** getP()
        {
            return this->p;
        }

};

int N;
int r, c;
int m[10][10];
Piece piece[NN];
int pi = 0;
void dump()
{
    for(int i = 0; i < pi; i++)
    {
        for(int j = 0; j < piece[i].getR(); j++)
        {
            for(int k = 0; k < piece[i].getC(); k++)
            {
                cout << piece[i].getP()[j][k];
            }
            cout << endl;
        }
        cout << endl;
    }
}
int main()
{
    freopen("d://1.text", "r", stdin);
    while (cin >> N && N)
    {
        memset(m, 0, sizeof(m));
        memset(piece, 0, sizeof(piece));
        int p[NN][NN];
        pi = 0;
        for(int i = 1; i <= N; i++)
        {
            scanf("%d %d", &r, &c);
            for(int j = 0; j < r; j++)
                for(int k = 0; k < c; k++)
                {
                    char t;
                    cin >> t;
                    if(t == 0)
                        p[j][k] = 0;
                    else
                        p[j][k] = i;
                }
            Piece pp(r, c, p);
            piece[pi++] = pp;
            cout<<"for end"<<endl;
        }
    }
    //dump();
    return 0;

}

输出

for end  //循环结束输出
delete   //删除pp对象
main end //main函数结束

//下面是5个delete 和 const int NN=5对应

delete 
delete
delete
delete
delete

//所以, delete 0 永远都是安全的

//注意前面有个  

memset(piece, 0, sizeof(piece));

 

写了一个bug----使用已经被删除的内存

标签:let   stream   ext   pac   memory   i++   ret   space   int   

原文地址:https://www.cnblogs.com/shuiyonglewodezzzzz/p/9165200.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!