首页 > 代码库 > C/C++ New与Delete (小例子)

C/C++ New与Delete (小例子)

转自:http://blog.csdn.net/chenzujie/article/details/7011639

 

 

先来看两段小程序:1)、#include <iostream.h>#include <String.h>void main(void){char *str1 = "just have fun";char *str2 = "happy day";char *sTmpPtr = new char[255];char *sMyStrPtr = new char[255];strcpy(sTmpPtr, str1);strcpy(sMyStrPtr, str2);delete  sMyStrPtr ;strcpy(sMyStrPtr, sTmpPtr);cout << sMyStrPtr << endl;}2)、#include <iostream.h>#include <String.h>void main(void){char *str1 = "just have fun";char *str2 = "happy day";char *sTmpPtr = new char[255];char *sMyStrPtr = new char[255];strcpy(sTmpPtr, str1);strcpy(sMyStrPtr, str2);delete  sMyStrPtr ;sMyStrPtr = sTmpPtr;cout << sMyStrPtr << endl;}第一段程序的输出会是乱码,因为delete sMyStrPtr,删除了sMyStrPtr所指向的内存空间,但作为一个指针sMyStrPtr依然存在,却没有指向内存,因此在strcpy里会执行*strDest++=*strSrc++,但strDest没有指向,所以*strDest++=*strSrc++并没有达到复制的效果,输出就乱码了。在第二段程序,delete之后,又把sTmpPtr赋值给了sMyStrPtr,sMyStrPtr有了指向,指向sTmpPtr的内存空间,所以可以正常输出。