不相交的动态内存可用分配的内存问题

时间:2019-03-29 01:39:05

标签: c heap-memory

我知道我的代码很粗糙,但是该程序可以按我想要的方式工作,但是退出程序时遇到了问题。我认为问题在于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

1 个答案:

答案 0 :(得分:0)

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

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

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

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

array = malloc(size * sizeof(STUDENT));
相关问题