disjoint Dynamic Memory免费分配的内存问题

问题描述 投票:0回答:1

我知道我的代码很粗糙,但程序按我的意思运行,但是我有一个退出程序的问题。我认为问题在于使用free(array)释放分配的内存。有人可以解释一下有什么问题并为这几行发布修复程序吗?

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
c heap-memory
1个回答
0
投票
array = malloc(size, sizeof(STUDENT));

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

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

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

array = malloc(size * sizeof(STUDENT));
© www.soinside.com 2019 - 2024. All rights reserved.