【发布时间】:2013-11-17 04:32:17
【问题描述】:
我提前道歉,但这有点长。
在我的程序中,我读入了学生的信息,但是当我去输出它时,它出来的时候是乱码,然后得到一个指针错误。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct student{
char *firstName;
char *lastName;
char id[10];
char gender;
int age;
double gpa;
};
void main()
{
int n;
struct student *classroom;
printf("How many students?");
scanf("%d",&n);
classroom = (struct student*) malloc(n*sizeof(struct student));
if (classroom == NULL)
exit(1);
readStudentsInformation(classroom,n);
outputStudents(classroom,n);
printf("The average age is %.2f.\n",averageAge(classroom,n));
printf("The average GPA is %.2f.\n",averageGpa(classroom,n));
sortByLastName(classroom,n);
outputStudents(classroom,n);
sortByID(classroom,n);
outputStudents(classroom,n);
sortByAge(classroom,n);
}
void outputStudents(struct student classroom[], int size)
{
int i;
for (i = 0; i < size; i++)
{
printf("%15s",classroom[i].firstName);
printf("%15s:",classroom[i].lastName);
printf("%14s,",classroom[i].id);
printf("%3c",classroom[i].gender);
printf("%5d",classroom[i].age);
printf("%5.2f",classroom[i].gpa);
}
}
输入: 有多少学生?2 名字?汤姆 姓氏?阿伦 身份证?2 性别?M 年龄?26 平均绩点?3.9 名字?弗兰克 姓氏?罗伯茨 身份证?1 性别?F 年龄?24 GPA?3.4'
输出:
Roberts Roberts: 2, M 26 3.90 : 1, F 24 3.40The average age is 25.00.
平均 GPA 为 3.65。 * 检测到 glibc * ./lab12: munmap_chunk(): 无效指针:0x00007fff30319a90 *
: 2, M 26 3.90Aborted (core dumped)
完整的代码在这里,但我不想复制200行堆栈溢出:http://codepad.org/LYpS6t5z
知道是什么原因造成的吗?
【问题讨论】:
-
munmap_chunk听起来像是free的一部分,这意味着您可能损坏了malloc的内存。 -
看起来你在用 temp 和你的成员指针做一些奇怪的事情[这至少会泄漏 mallocd 内存,当你释放成员时会出现段错误]
-
valgrind 非常擅长发现这些问题。
-
您践踏了未分配的内存。就像写到数组的末尾一样。使用 -g 编译,然后运行 valgrind。它会告诉你从某事结束的那一行。
-
奇怪的东西我的意思是为这些指针分配一个堆栈引用[并且在这个过程中泄漏了释放你的 malloc 内存的所有可能性]