[英]Program crashes on a specific value when i try to free() the arrays in a pointer array
我試圖使用一個動態數組來計算平均積分,但是當我使用這些值運行時,我的程序崩潰了:
如果我這樣做,它不會崩潰:
如果我用free()刪除for循環; 內
for (i=0 ; i<classes ; i++)
{ //free each individual 2unit array first
free(grades[i]); //This line doesnt work
}
它運行正常,但我不想這樣做,因為即時通訊告訴我不要這樣做。
這是代碼,我試圖盡可能地刪除不必要的部分
#include<stdio.h>
#include<stdlib.h>
void fillArray(int **grades,int start,int finish)
{
int i;
for(i=start;i<finish;i++)
{
printf("Enter grade for Class %d: ",i+1);
scanf("%d",&grades[i][0]);
printf("Enter Credit for Class %d: ",i+1);
scanf("%d",&grades[i][1]);
}
}
void expandArray(int **grades,int oldSize,int newSize)
{
*grades = (int *)realloc(*grades,newSize*sizeof(int*)); //expanding the pointer array
int i;
for(i=oldSize;i<newSize;i++) //filling it with 2 unit arrays per class
{
grades[i] = (int *)malloc(2*sizeof(int));
}
fillArray(grades,oldSize,newSize);
}
int main()
{
int classes,oldClasses;
printf("Enter number of classes: ");
scanf("%d",&classes);
int **grades = (int **)malloc(classes*sizeof(int*)); //creating an array to store 2unit arrays(pointer array)
int i;
for(i=0;i<classes;i++) //filling the pointer array with 2 unit arrays per class
{
grades[i] = (int *)malloc(2*sizeof(int));
}
printf("Enter grades for each classes: \n");
fillArray(grades,0,classes); // this 0 here means we start at the index 0, that parameter is later used to start at the lastIndex+1
oldClasses = classes; // copied the value of classes to oldClasses instead of taking the new one as newClasses to avoid confusion.
printf("Enter new number of classes: ");
scanf("%d",&classes);
expandArray(grades,oldClasses,classes);
printf("This line works!");
for (i=0 ; i<classes ; i++)
{ //free each individual 2unit array first
free(grades[i]); //This line doesnt work
}
printf("This won't get printed with the value 3...");
free(grades); //free the pointer array (This one also works)
return 0;
}
檢查main()
的classes
值
當您第二次獲得分類的數量時,您正在函數expandArray()
中重新分配內存,並且該擴展在該函數之外不可見,因此在釋放時,您可能會嘗試釋放一些未分配的內存,從而導致崩潰。
expandArray
實際上是更新grades
這是一個int**
里面卻正在更新*grades
:您正在擴大的第一陣列從2年級到newSize
的成績,而你想添加一個新的完整的類。
您要在函數中傳遞要修改的對象的地址 ,因此應傳遞int***
。
void expandArray(int ***grades,int oldSize,int newSize)
{
grades = realloc(grades, newSize*sizeof(int*));
// ...
}
注意:但是3D指針通常不是一個好習慣:您可能想要修改expandArray
以便它返回一個新的int**
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.