当我尝试释放()指针数组中的数组时,程序在特定值上崩溃

时间:2014-12-18 12:51:23

标签: c arrays dynamic crash realloc

我试图使用动态数组来计算平均值,但是当我使用值运行时我的程序崩溃了:

  • 2 1 1 1 1 3 1 1
如果我这样做,它不会崩溃:

  • 2 1 1 1 1 4 1 1 1 1

如果我用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;
}

2 个答案:

答案 0 :(得分:0)

检查classes

main()的值

当您第二次在函数expandArray()内重新分配内存并且在该函数之外看不到此扩展时,如果您获得了分类数,那么当您释放时,您可能会尝试释放一些未分配的内存,因此崩溃

答案 1 :(得分:0)

expandArray实际上正在更新grades int**,但您正在更新*grades:您正在扩展第一个数组当你想要添加一个新的整个班级时,强> 2 成绩为 newSize 成绩。

您想要在函数中传递要修改的对象的地址,因此您应该传递int***

void expandArray(int ***grades,int oldSize,int newSize)
{
    grades = realloc(grades, newSize*sizeof(int*));
    // ...
}

注意:但3D指针通常不是一个好习惯:您可能想要修改expandArray,以便它返回一个新的int**