释放动态内存的问题?
你们看我的主函数的代码。为什么外部循环那个释放内存的语句我感觉有问题呢?每次进行了几次循环之后
我就感觉有崩溃的感觉!!
#include<cstdio>
#include<stdlib.h>
#include<crtdbg.h>
#include<iostream>
#include"Name.h"
using namespace std;
void init(Name* names,int count)
{
char* fi_rstnames[]={"charles","mary","arthur","emily","john"};
int fi_rstsize=sizeof (fi_rstnames)/sizeof(fi_rstnames[0]);
char* secondnames[]={"dickens","shelley","miller","bronte","steinbeck"};
int secondsize=sizeof(secondnames)/sizeof(secondnames[0]);
char* fi_rst=fi_rstnames[0];
char* second=secondnames[0];
for(int i=0;i<count;i++)
{
if(i%2)
fi_rst=fi_rstnames[i%fi_rstsize];
else
second=secondnames[i%secondsize];
names[i]=Name(fi_rst,second);
}
}
int main(int argc,char* argv[])
{
FILE *pout(nullptr);
errno_t err=freopen_s(&pout,"debug_out_txt","w",stdout);
if(err)
cout<<"error on freopen "<<endl;
_CrtSetDbgFlag(_CRTDBG_LEAK_CHECK_DF|_CRTDBG_ALLOC_MEM_DF);//程序退出时执行内存泄露检测
_CrtSetReportMode(_CRT_WARN,_CRTDBG_MODE_FILE);//将检测到的内存泄露输出一般目的地
_CrtSetReportFile(_CRT_WARN,_CRTDBG_FILE_STDOUT);//将内存泄漏检测到的输出设定为标准流
Name myname("Ivor","Horton");
char thename[12];
cout<<"\nThe name is "<<myname.getname(thename);
char* pname=new char[myname.getnamelength()+1];
cout<<"\nThe name is "<<myname.getname(pname);
const int arraysize=5;
Name names[arraysize];
init(names,arraysize);
char* phrase=nullptr;
char* iname=nullptr;
char* jname=nullptr;
for(int i=0;i<arraysize;i++)
{
iname=new char[names[i].getnamelength()+1];
for(int j=i+1;j<arraysize;j++)
{
if(names[i]<names[j])
phrase=" less than ";
else if(names[i]<names[j])
phrase=" greater than ";
else if(names[i]==names[j])
phrase=" equal to ";
jname=new char[names[j].getnamelength()+1];
cout<<endl<<names[j].getname(iname)<<" is "<<phrase
<<names[j].getname(jname);
delete[] jname;
}
delete[] iname;//进行多次循环之后。发现在某一次外部循环。外部循环包括的指针数组进行释放内存的时候感觉有问题。~WHY
iname=nullptr;
}
delete[] pname;
cout<<endl;
return 0;
}
[解决办法]
兄弟,编程是一个很严肃的问题,怎么能凭感觉形式的,最不济也得凭现象啊。。。
[解决办法]
等崩溃了 你再感觉吧!
一个new对应一次delete就好了!担心啥!
[解决办法]
没啥问题
new的结果最好判断下
new和delete是对称的
[解决办法]
c++通常的做法是捕获异常而不判断new是否成功。