遇到个内存释放问题求大神帮帮忙
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <time.h>
typedef struct Student
{
int id;
char name[10];
char *code;
int pages;
}student;
int random(int from,int to);
char *newid();
int main(int argc, char* argv[])
{
const int N=100;
student *st=(student*)malloc(N*sizeof(student));
assert(st!=0);
char temp[4];
//st[0].code=newid();
//printf("%s",st[0].code);
FILE *fp=0;
char *filename="D:\\xueC++\\project\\test427_1\\student.xml";
fp=fopen(filename,"w");
assert(fp!=0);
srand(time(0l));
for(int i=0;i<N;i++)
{
st[i].id=10111+i;
itoa(i+100,temp,10);
strcpy(st[i].name,"xyzp");
strcat(st[i].name,temp);
printf("%s\n",st[i].name);
st[i].code=(char*)malloc(strlen(newid())+1);
assert(st[i].code!=0);
st[i].code=newid();
printf("%s\n",st[i].code);
st[i].pages=random(100,1000);
}
fprintf(fp, "%s\n",
"<?xml version=\'1.0\' encoding=\'ISO-8859-1\' standalone=\'Yes\' ?>");
fprintf(fp, "%s\n", "<Students>");
for(i=0;i<N;i++)
{
fprintf(fp,"\t%s\n","<student>");
fprintf(fp,"\t\t%s%d%s\n","<id>",st[i].id,"</id>");
fprintf(fp,"\t\t%s%s%s\n","<name>",st[i].name,"</name>");
fprintf(fp,"\t\t%s%s%s\n","<code>",st[i].code,"</code>");
fprintf(fp,"\t\t%s%d%s\n","<pages>",st[i].pages,"</pages>");
fprintf(fp,"\t%s\n","</student>");
fprintf(fp,"\n");
}
fprintf(fp, "%s\n", "</Students>");
fclose(fp);
for(i=0;i<N;i++)
{
free(st[i].code);
}
free(st);
st=0;
printf("\nHello World!\n");
return 0;
}
int random(int from,int to)
{
return (rand()%(to-from)+from);
}
char *newid()
{
char arr[]={'A','B','C','D','E','F','G','H','I','J',
'K','L','M','N','O','P','Q','R','S','T','U','V','W','X',
'Y','Z','0','1','2','3','4','5','6','7','8','9'};
char *arry=(char*)malloc(sizeof(arr));
int len=sizeof(arr)/sizeof(arr[0]);
for(int j=0;j<36;j++)
{
if(j==8||j==13||j==18||j==23)
arry[j]='-';
else
arry[j]=arr[rand()%len];
}
arry[j]='\0';
return arry;
}
[解决办法]
st[i].code = (char*)malloc(strlen(newid()) + 1);
assert(st[i].code != 0);
st[i].code = newid();
第一句,code已经被赋值, 然后第三局,继续被赋值,而newid已经会申请空间放新的id.
所以, 之前的那个malloc多余, 还有 strlen()里面的newid,也多余.
泄露两次.
所以 st[i].code = (char*)malloc(strlen(newid()) + 1);删掉,没用.
[解决办法]
st[i].code=(char*)malloc(strlen(newid())+1);
assert(st[i].code!=0);
st[i].code=newid();
前两句没用,还有你那个 newid()里
char *arry=(char*)malloc(sizeof(arr));
应该是char *arry=(char*)malloc(sizeof(arr)+1);吧,应该用来放\0