Malloc()为整数创建一个新的大小用于数学 - 需要指导

时间:2017-01-24 10:02:08

标签: c memory malloc

我的目标是创建一个大小超过4个字节的整数类型,如果我使用long,则为8。我尝试使用malloc尝试在内存中为更大的整数提供更多字节,但它仍然在第31次迭代时打破(给出负数)。这是我的代码:

int main()
{
    int x = 31; //(normally an int can do up to 30 without going negative so this is my test number)
    int i;

    int *bigNum = NULL;
    bigNum = malloc((sizeof(int)*2));
    *bigNum = 1;
    for (i=0; i<x; i++) {
          *bigNum = *bigNum * 2;
          printf("%d \n", *bigNum);
    }
    free(bigNum);
}

输出:

2
4
...
..
...
1073741824
-2147483648

3 个答案:

答案 0 :(得分:1)

虽然您为整数分配了更多内存,但系统的其他任何部分都不知道这一点,包括:

  • 编译器不知道这一点;

  • CPU芯片不知道这一点。

  • printf不知道这一点。

所以所有计算都是使用原生int大小进行的。

请注意,您不能告诉CPU芯片您使用更大的整数;这是芯片的物理/设计限制。

答案 1 :(得分:0)

取消引用int *会为您提供int,无论 为您分配多少额外内存。

如果您想要一个能够容纳更多信息的数据类型,请尝试使用long(尽管保证至少 int一样大)

如果要处理超出实现提供的整数,请使用bignum库,如MPIR

答案 2 :(得分:0)

  

目标是创建一个更大的整数类型

要处理多个int整数,代码还需要每个基本操作的支持函数:

int main(void) {
    int x = 31;

    RandBigNum *bigNum = RandBigNum_Init();
    RandBigNum_Assign_int(bigNum, 1);
    for (int i=0; i<x; i++) {
      RandBigNum_Muliply_int(bigNum, 2);
      RandBigNum_Print(bigNum);
      printf(" \n");
    }

现在,如何实现这一切?很多方法。

以下是简单,不完整且未经测试的。它不一定是良好的方法,而是提供完成大数库所需细节的初步想法。

//  Numbers are all positive.  The first array element is the size of the number
typedef unsigned RandBigNum;

#define RandBigNum_MAXP1 (UINT_MAX + 1ull)

RandBigNum *RandBigNum_Init(void) {
  return calloc(1, sizeof *RandBigNum);
}

void RandBigNum_Muliply_int(RandBigNum *x, unsigned scale) {
  unsigned carry = 0;
  for (unsigned i = 1; i <= x[0]; i++) {
    unsigned long long product = 1ull * x[i] * scale + carry;
    x[i] = product % RandBigNum_MAXP1;
    carry *= product / RandBigNum_MAXP1;
  }
  if (carry) {
    unsigned n = x[0] + 2;
    x = realloc(x, sizeof *x * n); // re-alloc check omitted
    x[x[0]] = carry;
    x[0]++;
  }
}

// many other functions