C 释放结构数组

C 释放结构数组,c,arrays,struct,malloc,C,Arrays,Struct,Malloc,我正在尝试释放一个结构数组,其中包含一个字符串数组,它们都是用malloc分配的,程序一直工作,直到我尝试用我创建的函数释放它,我得到了内核转储 这是我的结构: name allocated array,courses-array of string,teach是一个分配的结构数组,我正试图逐个释放它 struct date { int day,month,year; }; struct lecturer { char * name; struct date birthdate; i

我正在尝试释放一个结构数组,其中包含一个字符串数组,它们都是用malloc分配的,程序一直工作,直到我尝试用我创建的函数释放它,我得到了内核转储

这是我的结构: name allocated array,courses-array of string,teach是一个分配的结构数组,我正试图逐个释放它

 struct date

{
    int day,month,year;
};
struct lecturer
{
char * name;
struct date birthdate;
int num_of_courses;
char ** courses;
};
这是我的职责:

void freeAndExit(struct lecturer* teach,int num)
{
  int i,j;
  for(i=ZERO;i<num;i++)
  {
    free(teach[i]->name);
    for(j=ZERO;j<teach[i]->num_of_courses;j++)
        free(teach[i]->courses[j]);
  }

free (teach[i]);
}
有什么想法吗? 编辑: 这就是我输入结构的方式

void InputLecturer(struct lecturer** teach,int num)
{
    int i;
    char temp[SIZE];
    getchar();
  teach=(struct lecturer*)malloc(sizeof(struct lecturer)*num);
   for(i=ZERO;i<num;i++)
   {
     printf("Please enter the lecturers name:\n");
     InputStr(temp);
     (*teach)[i].name=(char*)malloc(sizeof(char)*strlen(temp));
     strcpy((*teach)[i].name,temp);
     printf("Please enter the birtday date:|Day|Month|Year|\n");
     scanf(" %d %d %d",&(*teach)[i].birthdate.day,&(*teach)[i].birthdate.month,&(*teach)[i].birthdate.year);
     printf("Enter the number of courses\n");
     scanf("%d",&(*teach)[i].num_of_courses);
     getchar();
     InputCourses(&(*teach)[i],(*teach)[i].num_of_courses);

   }


}
void InputCourses(struct lecturer* teach,int num)
{
    int i;
    char temp[SIZE];
   teach->courses=(char**)malloc(sizeof(char)*num);
   for(i=ZERO;i<num;i++)
   {
      printf("Please enter course name number %d\n",i+1);
      InputStr(temp);
      teach->courses[i]=(char*)malloc(sizeof(char)*strlen(temp));
      strcpy(teach->courses[i],temp);
   }

}

首先,这一行在循环之外,因此i的值将在分配给teach的边界之外。其次,teach[i]是一个结构讲师,所以它没有分配内存,所以没有什么可以释放的

free (teach[i]);
需要释放的是教自己,所以用这一行替换上面的行

free (teach);
您还应该确保为任何字符串分配足够的内存—它们总是比您认为存储终止NUL字符所需的内存多。例如,这条线

teach->courses[i]=(char*)malloc(sizeof(char)*strlen(temp));
应该是

teach->courses[i]=malloc(sizeof(char)*(strlen(temp)+1));
注意:您不需要在C中强制转换malloc的返回值

如果没有为字符串分配足够的空间,则会调用未定义的行为,因为当您将字符串strcpy到新分配的内存中时,NUL终止字符将被写入超出已分配内存的范围,稍后可能会被某个合法所有者覆盖

或者,您可以将malloc和strcpy调用组合成一个对strdup的调用,该调用将分配适当的内存量并为您复制现有字符串

teach->courses[i]=strdup(temp);

虽然这可能是由于一些原因造成的,但我将从您分配这些结构的方式开始。你能编辑这个问题来显示分配吗?OT:但是用像零这样的花哨的东西替换“0”是没有意义的,添加只会增加混乱。你的意思是零,然后写0。我编辑并输入了结构,零是讲师对我的项目的要求。。说来话长。@AlexAlex在调用freeAndExit&teach,numTeach;之前,在main中如何声明和使用teach;?您确定您没有获取指针的地址,并以结构为结尾吗**?你的意思是只做免费的教学吗,numTeach?你也做自由教育[我];在freeAndExit中,但teach[我]会给你一个结构型教师,而不是结构型教师*。那应该是免费教学吗;?哈哈-换一个不同的教练,零的东西太可笑了不,我不是说免费教学(我);应该在循环中移动-我是说它甚至不应该存在,我的坏。我忽略了将teach声明为一个简单数组而不是指针到指针的指针。你说得对。我已经投了票,所以我不能投两次票
teach->courses[i]=strdup(temp);