简体   繁体   English

二维GMP整数矩阵运算后的内存分配问题

[英]Problem of memory allocation after operations on 2D GMP integer matrix

I am trying to use 2D GMP integer matrix.我正在尝试使用 2D GMP 整数矩阵。 I followed this solution https://stackoverflow.com/a/49987570/7462275 .我遵循了这个解决方案https://stackoverflow.com/a/49987570/7462275

This is my program这是我的程序

#include <gmp.h>
#include <stdio.h>
#include <stdlib.h>

int main() {
    const size_t size = 4 ; 
    mpz_t **my_matrix;

    my_matrix=malloc(size*sizeof(mpz_t*));
    my_matrix[0]=malloc(size*size*sizeof(mpz_t));
    for(int i=1;i<size;i++)
        my_matrix[i]=my_matrix[i-1]+(size*sizeof(mpz_t));
   
   
    for (int i=0; i<size;i++)
        for (int j=0; j<size;j++) {
            mpz_init(my_matrix[i][j]);
            mpz_set_ui(my_matrix[i][j],1);
        }


    for (int exponent=1; exponent<20;exponent++)
    
        for (int i=0; i<size;i++)
            for (int j=0; j<size;j++) {
                mpz_mul_ui(my_matrix[i][j],my_matrix[i][j],10);
        }

}

It works as expected.它按预期工作。 The results of calculation are correct.计算结果正确。

But when limit of exponent is increased (eg 100) in the for loop ( for (int exponent=1; exponent<100;exponent++ ) ), a segmentation error(core dumped) happens at running time.但是当for循环 ( for (int exponent=1; exponent<100;exponent++ ) ) 中的指数限制增加(例如 100)时,在运行时会发生分段错误(核心转储)。 How can I solve it?我该如何解决?

This is needlessly complicated, slow and error prone:这是不必要的复杂、缓慢且容易出错的:

mpz_t **my_matrix;

my_matrix=malloc(size*sizeof(mpz_t*));
my_matrix[0]=malloc(size*size*sizeof(mpz_t));
for(int i=1;i<size;i++)
    my_matrix[i]=my_matrix[i-1]+(size*sizeof(mpz_t));

Actually the my_matrix[i-1]+(size*sizeof(mpz_t));实际上是my_matrix[i-1]+(size*sizeof(mpz_t)); part does pointer arithmetic on type mpz_t so you get offsets of sizeof(mpz_t) times (size*sizeof(mpz_t) bytes, which is all wrong.部分对类型mpz_t进行指针运算,因此您得到sizeof(mpz_t)(size*sizeof(mpz_t)字节)的偏移量,这是完全错误的。

Replace it with:将其替换为:

mpz_t (*my_matrix)[size] = malloc( sizeof(mpz_t[size][size]) );

if(my_matrix == NULL)
{
  /* error handling */
}

(And in the end free(my_matrix); ) (最后free(my_matrix);

Now you can use my_matrix[i][j] but you actually have a proper 2D array in a contiguously allocated chunk.现在您可以使用my_matrix[i][j]但您实际上在连续分配的块中有一个适当的二维数组。 For details check out Correctly allocating multi-dimensional arrays .有关详细信息,请查看正确分配多维数组

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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