class
is a local variable within the getClassInfo()
function, which means that it ceases to exist when that function returns. The return class;
statement returns a pointer that's no longer valid by the time the caller receives it.
You should declare class
as a student*
and allocate it dynamically with malloc()
, just like you do for the students themselves. That allocates it on the heap, so it continues to exist until you explicitly free()
it. You'll want to do malloc(sizeof(student) * CLASS_SIZE)
to allocate contiguous space for all the student structures.
You're right that not freeing the student
structures allocated in the loop is a bug (specifically, a memory leak). You don't actually need to dynamically allocate students at all; you can just store the student number and grade into class[i].studentNr
and class[i].grade
.