繁体   English   中英

当我尝试对指针数组中的数组进行free()时,程序在特定值上崩溃

[英]Program crashes on a specific value when i try to free() the arrays in a pointer array

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

  • 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;
}

检查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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM