当更多内存被malloced时,计算机会冻结

时间:2014-07-08 07:23:05

标签: c ubuntu memory

我正在尝试运行一个C程序,该程序根据用户给出的输入对内存进行malloc。

每当我输入大到1000000000的东西而不是返回NULL值时,我的Ubuntu 14.04机器就会完全冻结!我很确定malloc是罪魁祸首......

但我很惊讶看到Ubuntu冻结了!

有没有人知道为什么会这样?

我的笔记本电脑配有12GB内存,i5处理器和500GB硬盘。和Ubutnu 14.04 OS

以下是代码:

#include<stdio.h>
#include<stdlib.h>
#define LEFT(x) (2*(x)+1)
#define RIGHT(x) (2*(x)+2)

long long int *err, *sorted, *size, *id;
short int *repeat;

void max_heapify(long long int *arr, long long int length, long long int index)
{
  long long int largest, left, right, temp, flag = 1;

  while (flag)
    {
      left = LEFT(index);
      right = RIGHT(index);

      if (left < length && arr[left] > arr[index])
    largest = left;
      else
    largest = index;

      if (right < length && arr[right] > arr[largest])
    largest = right;

      if (largest != index)
    {
      temp = arr[index];
      arr[index] = arr[largest];
      arr[largest] = temp;
      index = largest;
    }
      else
    flag = 0;
    }
}

void build_max_heap(long long int *arr, long long int length)
{
  long long int i, j;
  j = (length / 2) - 1;
  for (i = j; i >= 0; i--)
    max_heapify(arr, length, i);
}

void heapsort(long long int *arr, long long int length)
{
  long long int i, temp, templength;

  build_max_heap(arr, length);

  templength = length;
  for (i = 0; i < templength; i++)
    {
      temp = arr[0]; // maximum number
      arr[0] = arr[length - 1];
      arr[length - 1] = temp;
      length--;
      max_heapify(arr, length, 0);
    }
}

int main()
{
  long long int n, k, p, i, j;
  scanf("%lld%lld%lld",&n, &k, &p);
  err = (long long int*)malloc((n + 1) * sizeof(long long int));
  //repeat = (short int*)calloc(1000000001 , sizeof(short int));
  sorted = (long long int*)malloc((n + 1) * sizeof(long long int));
  j = 0;
  for(i = 0; i < n; i++)
    {
      scanf("%lld",&err[i]);
      sorted[j++] = err[i];
    }

  heapsort(sorted, j);

  for(i = 0; i < j; i++)
    printf("%lld, ",sorted[i]);

  //These malloc statements cause the problem!! 
  id = (long long int*)malloc((sorted[j - 1] + 1) * sizeof(long long int));
  size = (long long int*)malloc((sorted[j - 1] + 1) * sizeof(long long int));

  for(i = 0; i <= sorted[j - 1]; i++)
    {
      id[i] = i;
      size[i] = 1;
    }

  return 0;
}

基本上我试图对数字进行排序,然后分配最大元素大小的数组。这个程序适用于较小的输入,但是当我输入

5 5 5 

1000000000 999999999 999999997 999999995 999999994

它冻结ubuntu ..我甚至添加条件来检查id或size是否为NULL但是没有帮助!如果系统无法分配那么多内存,那么它应该返回NULL但系统冻结!这段代码在MAC上工作正常!

谢谢!

0 个答案:

没有答案