disjoint Dynamic Memory free allocated memory 问题

disjoint Dynamic Memory free allocated memory problem

我知道我的代码很粗糙,但程序按我想要的方式运行,但我在退出程序时遇到问题。我认为问题在于 free(array) 释放分配的内存。有人可以解释一下哪里出了问题并 post 修复那几行吗?

int main() {
        int choice;
        STUDENT *array;
        int size = 0;
        int counter = 0;
        int i, j;
        srand((unsigned)time(NULL));

        printf("\n\tEnter the size for the array: \n");
        scanf_s("%i", &size);

        array = malloc(size, sizeof(STUDENT));

        if (array == NULL) {
            printf("Error Allocated Memory\n");
            PAUSE;
            exit(-1);
        }//End If
        else {
            printf("The Memory Has Been Allocated\n");
            PAUSE;
        }//end Else

        //Enter elements into the array
        for (i = 0; i < size; i++) {
            printf("\nPlease enter a student ID number: ");
            scanf("%d", &array->stuId[i]);
            //populate grades for each stuID
            for (j = 0; j < size; j++) {
                array->exam1[j] = rand() % 100;
                array->exam2[j] = rand() % 100;
                array->exam3[j] = rand() % 100;
                array->exam4[j] = rand() % 100;
            }
        }

        do {
            choice = getChoice();
            switch (choice) {

            case 1: //Display All Student Records
                studentRecords(*array, size);
                break;
            case 2: //Display Student Average
                displayAve(array, size);
                break;
            case 3: //Quit
                printf("\n\tThank You For Using The Program\n");
                PAUSE;
                break;
            default:
                printf("\n\tERROR-- Try Again...\n");
                PAUSE;
                break;
            }
        } while (choice != 3);

        free(array);
        exit(-1);
    }//End Main
array = malloc(size, sizeof(STUDENT));

Malloc 不接受 2 个参数,只接受要分配的字节数。两种解决方案:

array = calloc(size, sizeof(STUDENT));

注意 calloc 将所有字节初始化为 0,或者您可以使用

array = malloc(size * sizeof(STUDENT));