- #1
cubanmissile
- 5
- 0
Homework Statement
Error:
Code:
warning: HEAP[Happy Birthday.exe]:
warning: Heap block at 006E15A8 modified at 006E1688 past requested size of d8
My Struct:
Code:
struct student { // Defines a student.
char firstName[NAMELENGTH], lastName[NAMELENGTH];
int day, month, year;
};
My Code (Partial):
Code:
void findClosestBirthday(FILE *file) {
char month[NAMELENGTH], targetStudentFirst[NAMELENGTH], targetStudentLast[NAMELENGTH];
int classes, students, targets, i, j;
struct student *class;
fscanf(file, "%d", &classes);
for(i = 0; i < classes; i++) { // Loops through all classes.
fscanf(file, "%d", &students);
class = (struct student*)malloc(students*sizeof(struct student));
for(j = 0; j < students; j++) { // Loops through all students.
fscanf(file, "%s %s %s %d %d", &class[j].firstName[0], &class[j].lastName[0], month, &class[j].day, &class[j].year);
class[j].month = monthToInt(month);
}
sortArray(class, 0, students); // Sorts students.
fscanf(file, "%d", &targets); // Scans in # of target students.
printf("Class %d\n", i+1);
for(j = 0; j < targets; j++) {
fscanf(file, "%s %s", &targetStudentFirst[0], &targetStudentLast[0]);
printBirthdays(class, students, targetStudentFirst, targetStudentLast);
}
printf("\n");
free(class); // Frees class.
}
}
At free(class) the program crashes. I AM modifying the array of structs in this function:
Code:
void swap(struct student *array, int i, int j) {
struct student temp;
temp = array[i];
array[i] = array[j];
array[j] = temp;
}
Homework Equations
None
The Attempt at a Solution
I've tried many.
First, I moved the free(class) to outside the class FOR loop and instead would realloc class based on new scanned in number of students. Would complain about heap overflow.
Secondly, I changed the swap function to this:
Code:
void swap(struct student *array, int i, int j) {
struct student temp;
// Make temp = array[i].
strcpy(temp.firstName, array[i].firstName);
strcpy(temp.lastName, array[i].lastName);
temp.day = array[i].day;
temp.month = array[i].month;
temp.year = array[i].year;
// Make array[i] = array[j].
strcpy(array[i].firstName, array[j].firstName);
strcpy(array[i].lastName, array[j].lastName);
array[i].day = array[j].day;
array[i].month = array[j].month;
array[i].year = array[j].year;
// Make array[j] = temp
strcpy(array[j].firstName, temp.firstName);
strcpy(array[j].lastName, temp.lastName);
array[j].day = temp.day;
array[j].month = temp.month;
array[j].year = temp.year;
}
Still complained about heap overflow. I'm confused as to why? I am sure I am following all practical conventions. I *assume* it has to do with my swap function, but cannot understand how to fix it. :(
If you guys need the entire program let me know, just would rather not post it all due to other students in my class maybe searching for the program so they copy. -_-
Thanks for ANY and ALL help/pointers! Let me know if you need the entire program.