I am trying to find two errors related to memory allocation in this code snippet. It was said in lecture that the first error was returning class , and the second was not freeing memory. I don't understand why the first is an error. The second one I am not sure of, but have a good idea of why.
For the first error, class is an array of students and the function getClassInfo returns a pointer to this array, seems fine to me.
I think I understand why memory should be free'd though. On each iteration of the for loop thisStudent is allocated memory by malloc and then class[i] is assigned to the value of thisStudent. On each iteration thisStudent is reassigned a new block of memory, but the last one is never free'd.
Any clarification as to why the first error is an error would be greatly appreciated! Thank you - Chris
#include <stdio.h>
#define CLASS_SIZE 500
typedef struct student {
int studentNr;
char grade;
} student;
student * getClassInfo(void){
int i;
student class[CLASS_SIZE];
for(i = 0; i < CLASS_SIZE; i++){
student * thisStudent = (student*) malloc(sizeof(student));
if(thisStudent == NULL) return(NULL);
scanf("%d %c", &(thisStudent->studentNr),&(thisStudent->grade));
class[i] = *thisStudent;
}
return class;
}
I do get an warning saying its return the address of a local variable, when compiling, but how is that a error related to memory allocation?
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
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.