當我正在運行在調試模式下面的代碼創建的.exe文件,它顯示了一些斷言失敗和程序崩潰但是當我運行從下面的釋放模式創建的相同的exe代碼,其工作正常。程序崩潰而重新分配的字符數組
請幫忙找出爲什麼我歌廳在調試模式下斷言失敗而不是在釋放模式。
#include<iostream>
using namespace std;
#include<string.h>
void main()
{
char *buf = new char[5]; //pre-allocated buffer
buf = "Hello";
delete [] buf;
getchar();
//cout<<buf;
//string *p = new (buf) string("hi"); //placement new
//string *q = new string("hi"); //ordinary heap allocation
}
注意,在這種情況下,你可以說'字符BUF [] =「你好」;',你會得到一個副本,你甚至不必取消分配。 – cHao
您很少需要C++中的C字符串,您應該使用''代替。在少數實際需要C頭文件的情況下,您應該使用C++頭文件(例如:)。 –
netcoder