为什么更大的malloc引起异常?

时间:2017-10-26 09:06:38

标签: c

我正在尝试修改Gauss-Jordan消除计算逆。有了这个,我拿一个矩阵,找到逆。虽然我可以使用malloc获取矩阵当我尝试将新矩阵的大小加倍时会导致异常

int main (int argc, char *argv[]) {
    FILE *train, *test;

    train = fopen(argv[1], "r");
    test = fopen(argv[2], "r");

    int abutes,examples;
    fscanf(train," %d %d",&abutes,&examples);  /*scan in number of examples and attributes*/

    int i,j, abuteswp;
    abuteswp=abutes+1;
    double (*trainA)[10000] = malloc(sizeof(double[10000][10000]));
    for (j=0;j<examples;j++){
        for ( i=1; i <abuteswp+1; i++){
            fscanf(train," %lf %[^,]",&trainA[j][i]);}}

            int p;
            /*add in 1s to matrix*/
            for (p=0;p<examples;p++)    {
                trainA[p][0]=1;
            }

            /*take out price*/
            double trainatt[examples][abuteswp];
            for ( i=0; i <examples; i++){
                for ( j=0;j<abuteswp;j++){
                    trainatt[i][j]=trainA[i][j];
                }
            }

在对矩阵进行一些计算之后,我需要对其进行扩充并使列加倍。我尝试测试后会导致异常

    double ** trainaug = NULL;
    int aug;
    aug=examples*2;
    trainaug = malloc (examples * sizeof(double *));

    for(i = 0; i < examples; i++)
    {
        trainaug[i] = malloc (aug * sizeof(double));
    }
    for(i = 0; i <examples; i++)
    {
        trainaug[i] = malloc (examples * sizeof(double));
    }
    for ( i=0; i <examples; i++){
        for ( j=0;j<examples;j++){
            trainaug[i][j]=trainmult[i][j];}
        }
        for ( i=0; i <examples; i++){
            for ( j=examples;j<aug;j++){
                trainaug[i][j]=0;}
            }
            for ( j=0;j<examples;j++){
                i=examples;
                trainaug[j][i]=1;
                i++;
            }

即使没有for循环,也会导致异常。我是以错误的方式做malloc还是我的代码不对?随着我的进展,我正在释放我的指针

0 个答案:

没有答案