现在的位置: 首页 > 综合 > 正文

C++中new与delete问题学习

2013年10月14日 ⁄ 综合 ⁄ 共 1483字 ⁄ 字号 评论关闭

C++newdelete问题学习

一.new chardelete问题

1. 问题程序

#include <iostream>

using namespace std;

void main()

{       

char* des = new char();

des = "testing!";

cout<<des<<endl;



delete des;  //这个delete需要吗



}

 

2. 错误

       当运行到delete时,程序出错!

 

3. 解答

v1

你用new申请了一个char空间,把它的地址保存在了des这个指针里面

然后你又把"testing!"这个常量字符串的地址赋给了des这个指针

于是,你之前用new申请的那个空间就丢失了,在程序结束系统回收全部内存前,那个空间就被标明被你使用但实际上你已经丢失它的地址没办法再使用它了,这就是最常见的内存泄露

delete出错理所当然,因为你delete的不是你new的那个空间。甲被乙骗了钱不能去法院起诉丙,丙是无辜的 

 

v2

1.

char* des = new char();

应该只分配一个byte的空间,而后面的des = "testing!";我猜楼主的意图是要将"testing!"放入des所指向的空间,很显然实际上是放不下去的。之所以输出有没有问题,是刚好将"testing"的首地址给了des,这就改变des的值,也就是des
= "testing!"
中的des,和前面的char* des = new char();已经不同了。

 

4. 正确代码

V1

#include <iostream>

using namespace std;

 

void main()

{

       char* des = new char[10];

       memset(des, 0, 10);

       strcpy(des, "testing!");

       cout << des << endl;

 

       delete des;

}

 

 

V2 严格版

 

#include <iostream>

using namespace std;

 

void main()

{

    char* des = new char[10];

    memset(des, 0, 10);

    strcpy(des, "testing!");

    cout << des << endl;

 

    delete[] des; // new[]和delete[]对应。但由于char是基本数据类型,所以6楼那样写应该也是没有问题的

}

 

 

二.new intdelete

1. 程序

#include <iostream>

using namespace std;

 

void main()

{

//一维整型指针

       int *a = new int [2];

       for (int i=0;i<2;i++)

       {

              a[i] = 1;

       }

 

       for (int i=0;i<2;i++)

       {

              printf("%d \n",a[i]);

       }

 

       delete[] a;

 

//二维整型指针

       int **b = new int *[2];

       for (int i=0;i<2;i++)

       {

              b[i] = new int [2];

       }

       for (int i=0;i<2;i++)

       {

              for (int j=0;j<2;j++)

              {

                     b[i][j] = 2;

              }

       }

 

       for (int i=0;i<2;i++)

       {

              for (int j=0;j<2;j++)

              {

                     printf("%d ",b[i][j]);

              }

              printf("\n");

       }

       

       for (int i=0;i<2;i++)

       {

              delete[] b[i];

       }

       delete[] b;

 

       system("pause");

}

 

 

2. 程序运行正常

       char以外的基本数据类型,在进行指针释放时一般不用考虑太多,主要是因为没有字符串的赋值(实质是地址的赋值)。

               

三.小结

       new的类型中,涉及到地址赋值,要千万小心!

抱歉!评论已关闭.