关于new和delete

感谢代码疯子的的这篇博客http://www.programlife.net/debugger-magic-number.html

先帖代码

 1 #include "stdafx.h"
 2 #include "iostream"
 3 #include "stdio.h"
 4 #include "string.h"
 5 #include "stdlib.h"
 6 using namespace std;
 7 const int nMaxSize=26;
 8 typedef struct Node
 9 {
10     Node * Next[nMaxSize];
11     Node()
12     {
13         for (int i=0;i<nMaxSize;i++)
14         {
15             Next[i]=NULL;
16         }
17     }
18 }Node,* pNode;
19 Node root;
20 typedef void * pdata;
21 void Insert(char * pStr)
22 {
23     Node * p=&root;
24     for (int i=0;i<strlen(pStr);i++)
25     {
26         int id=pStr[i]-'a';
27         if (p->Next[id]!=NULL)
28         {
29             printf("test log\n");
30         }
31         else
32         {
33             p->Next[id]=new Node();
34         }
35     }
36 
37 }
38 void Delete(pNode p)
39 {
40     if (p==NULL) return;
41     for (int i=0;i<nMaxSize;i++)
42     {
43         Delete(p->Next[i]);
44         p->Next[i]=NULL;//添加这一句,解决二次delete
45     }
46     if (p==&root)
47     return;
48     delete p;
49     p=NULL;
50 }
51 void te(int& a)
52 {
53 
54     a=0;
55 }
56 void te2(void* & pd)
57 //void te2(pdata& pd)
58 {
59 
60     pd=NULL;
61 }
62 int _tmain(int argc, _TCHAR* argv[])
63 {
64     char szBuffer[16];
65     unsigned int nTmp = 0;
66     sprintf(szBuffer, "0x%X", -20);
67     nTmp = strtoul(szBuffer, NULL, 16);
68     printf("%u\n", nTmp);
69 
70     int var0=0;
71     printf("Insert a string\n");
72     Insert("a");
73     Delete(&root);
74     printf("Insert the same string again\n");
75     Insert("a");
76     Delete(&root);
77 
78     int var1=4;
79     te(var1);
80     int * pvar1=&var1;
81     pdata tp=(pdata)pvar1;
82     //pdata tp;
83     te2(tp);
84     //te2((pdata)pvar1);//错误的写法,编译通不过
85     //te(2);
86     int *p1 = new int();
87     int *p2 = p1;
88     delete p1;
89     p1 = NULL;
90     scanf("%d",&var0);
91     return 0;
92 }

搞明白了typedef和函数引用型参数的问题。

测试发现,56、57行效果是一样的,第83行就能实现将tp置为NULL,84行直接编译通不过。

还是学的不精通,到底编译器内部发生了什么不知道,看样子还得学习汇编啊

上述代码除了改动了几行,完全转载自http://www.programlife.net

posted on 2013-07-19 14:58  zhiying678  阅读(180)  评论(0编辑  收藏  举报

导航