64,653
社区成员
发帖
与我相关
我的任务
分享
#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;
}
//使用动态分配
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
int i,L;
char *p;
void main() {
for (i=0;i<20000;i++) {
L=rand();
p=malloc(L);
if (NULL==p) {
printf("malloc error!\n");
continue;
}
memset(p,0,L);
free(p);
}
}
//不使用动态分配
#include <stdio.h>
#include <stdlib.h>
#include <memory.h>
#define MAXLEN 30000
int i,L;
char buf[MAXLEN];
char *p;
void main() {
p=&buf[0];
for (i=0;i<20000;i++) {
L=rand();
if (L>MAXLEN) {
printf("L>MAXLEN==%d, ignore spilth.\n",MAXLEN);
L=MAXLEN;
}
memset(p,0,L);
}
}
个人倾向不使用动态分配。