添加的值不会正确保存到malloc数组。我忽略了内存泄漏吗?

时间:2014-09-24 13:01:27

标签: c memory-leaks struct malloc realloc

我正在尝试将值保存到动态分配的结构数组中。该程序在调用malloc的for循环内正常工作并正确打印值,但一旦for循环结束,我再次尝试打印seg错误。

这是带有结构定义

的标头
 typedef struct{
  char student_name[100];
  int stdnt_id;
  int courses[4];
  int grades[4][10];
  int number_courses;
  }students;

typedef struct{
  char course_name[100];
  int course_id;
  int course_students[100];
  int number_students;
  }courses;

typedef struct{             
  int number_courses;                           
  int number_students;
  }useful_numbers;

这就是代码。

#include <stdio.h>
#include <stdlib.h>
#include "structures.h"

useful_numbers numbers;
students **student;
courses **course;

void add_course(void)
{
putchar('\n');
int x, y, z, new, tmp;
printf("How many courses are you adding? ");
scanf("%d", &new);
getchar();
tmp=numbers.number_courses;
if(numbers.number_courses>0)
    {
    courses **course=(courses **)realloc(course, sizeof(courses *)*(new+numbers.number_courses));
    if(NULL==course)
        {
        printf("There was a problem in malloc\n");
        exit(1);
        }
    for(x=tmp; x<new+tmp; x++)
        {
        course[x]=(courses *)malloc(sizeof(courses));
        if(NULL==course[x])
            {
            printf("There was a problem in malloc\n");
            exit(2);
            }
        printf("Print the name of course number %d: ", x+1);
        gets(course[x]->course_name);
        printf("Print the id number for %s: ", course[x]->course_name);             
        scanf("%d", &course[x]->course_id);                                     
        getchar();
        numbers.number_courses++;                                                                       
        }
    }
if(numbers.number_courses==0)
    {
    courses **course=(courses **)malloc(new*sizeof(courses *));
    if(NULL==course)
        {
        printf("There was a problem in malloc\n");
        exit(3);
        }
    for(x=0; x<new; x++)
        {
        course[x]=(courses *)malloc(sizeof(courses));
        if(NULL==course[x])
            {
            printf("There was a problem in malloc\n");
            exit(4);
            }
        printf("Print the name of course number %d: ", x+1);
        scanf("%s", &course[x]->course_name);
        getchar();
        printf("Print the id for %s: ", course[x]->course_name);
        scanf("%d", &course[x]->course_id);
        getchar();
        printf("%s\t%d\t%d\t%d\n", course[x]->course_name, course[x]->course_id, numbers.number_courses, x);
        numbers.number_courses++;
        }
    }
for(y=0; y<numbers.number_courses; y++)
    {
    printf("%d\t%d\n", course[y]->course_id, numbers.number_courses);
    }
return;

}

1 个答案:

答案 0 :(得分:1)

if语句中,您声明了一个新的局部变量courses,它隐藏了同名的全局变量:

courses **course=(courses **)malloc(....);

最后的打印使用全局变量,但仍然是NULL。您想要设置现有的全局变量:

course=(courses **)malloc(....);