new delete的問題

#include "stdafx.h"
#include "iostream"
using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
 char *p=new char [10];
 p="012345678";
 delete []p;
 return 0;
}

這段程序如果不delete[]p則完全可以打印出cout<<p;原因在於"012345678"這是在常量區分配的,這樣

就導致給P重新指向,這樣的結果也就是說new char[10]的空間不能被p再指向,所以delete時肯定會出問題

因爲new分配的是在堆上的。修改上面的程序

————————————————————————————————————————————————

#include "stdafx.h"
#include "iostream"
using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
 char *p=new char [10];
 char *q=p;
 p="012345678";//如果想實現正常的賦值 可以用strcpy

 cout<<&p <<"   "<< &q;
 delete []q;
 int i;
 cin>>i;
 return 0;
}

此程序可以正常釋放正確

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章