【发布时间】:2009-04-15 17:46:24
【问题描述】:
这个小程序有问题:
已更新(根据某些要求,我已将所有内容都包含在此处,以便明确我在做什么。抱歉,它太长了): Student.h 文件:
typedef struct Student {
char *name;
int age;
char *major;
char *toString;
} *Student;
extern Student newStudent(char *name, int age, char *major);
Student.c 文件: c
har *studentToString(Student s);
static void error(char *s) {
fprintf(stderr,"%s:%d %s\n",__FILE__,__LINE__,s);
exit(1);
}
extern Student newStudent(char *name, int age, char *major) {
Student s;
if (!(s=(Student)malloc(sizeof(*s)))){
error("out of memory");
}
s->name=name;
s->age=age;
s->major=major;
s->toString = studentToString(s);
return s;
}
char *studentToString(Student s) {
const int size=3;
char age[size+1];
snprintf(age,size,"%d",s->age);
char *line=newString();
line=catString(line,"<");
line=catString(line,s->name);
line=catString(line," ");
line=catString(line,age);
line=catString(line," ");
line=catString(line,s->major);
line=catString(line,">");
return line;
}
Students.c 文件:
static void error(char *s) {
fprintf(stderr,"%s:%d %s\n",__FILE__,__LINE__,s);
exit(1);
}
static StudentList alloc(StudentList students, Student student) {
StudentList p;
if (!(p=(StudentList)malloc(sizeof(*p)))){
error("out of memory");}
p->student=student;
p->students=students;
return p;
}
extern Students newStudents() {
Students p;
if (!(p=(Students)malloc(sizeof(*p)))){
error("out of memory");
}
p->cursor=0;
p->students=0;
return p;
}
extern void addStudent(Students students, Student student) {
StudentList p=students->students;
if (!p) {
students->students=alloc(0,student);
return;
}
while (p->students)
p=p->students;
p->students=alloc(0,student);
}
extern void initStudent(Students students) {
students->cursor=students->students;
}
extern Student currStudent(Students students) {
StudentList cursor=students->cursor;
if (!cursor)
return 0;
return cursor->student;
}
extern void nextStudent(Students students) {
students->cursor=students->cursor->students;
}
还有我的主要方法:
int main() {
Students students=newStudents();
addStudent(students,newStudent("Julie",22,"CS"));
addStudent(students,newStudent("Trevor",32,"EE"));
for (initStudent(students);
currStudent(students);
nextStudent(students)) {
char *line=currStudent(students)->toString;
printf("%s\n",line);
free(currStudent(students));
free(line);
}
free(students->students);
free(students);
return 0;
}
我正在使用 valgrind 来检查内存泄漏,它弹出以下错误:
8 bytes in 1 blocks are definitely lost in loss record 1 of 1
==9520== at 0x40054E5: malloc (vg_replace_malloc.c:149)
==9520== by 0x8048908: alloc (Students.c:13)
==9520== by 0x80489EB: addStudent (Students.c:42)
==9520== by 0x804882E: main (StudentList.c:10)
我知道我需要释放 alloc 函数中为 p 分配的内存,但我应该在哪里调用 free(p)?还是我做错了什么?请帮忙!
【问题讨论】:
-
StudentList 是 Student* 的 typedef 吗?
-
您还应该包含 main() 以跟踪泄漏
-
我们相当确定 student 是一个简单的结构体。我们对 Student 和 StudentList 的定义更感兴趣。
-
是的,不知道 Stundents 和 StudentList 有点令人困惑。
-
隐藏指针的 typedef 很糟糕。至少命名它,以便有一些迹象表明它是一个指针。
标签: c pointers memory-leaks