gpt4 book ai didi

c - 不相交动态内存释放分配内存问题

转载 作者:行者123 更新时间:2023-11-30 16:20:05 25 4
gpt4 key购买 nike

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

最佳答案

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

Malloc 不采用 2 个参数,仅采用要分配的字节数。两种解决方案:

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

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

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

关于c - 不相交动态内存释放分配内存问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55409332/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com