如何在linux中使用C分配大型数组

时间:2016-04-23 10:44:20

标签: c linux memory allocation

有没有办法分配这个大小的数组:

unsigned long M[2000][900000] ;

这是我运行程序时得到的结果(编译期间没有错误)。

enter image description here

Processus arrêté (Process stopped)  

1 个答案:

答案 0 :(得分:6)

unsigned long (*pM)[2000][900000] = malloc(sizeof *pM);

完成这项工作。

像这样使用

#define ROWS_MAX (2000)
#define COLUMNS_MAX (900000)

...

unsigned long (*pM)[ROWS_MAX][COLUMNS_MAX] = malloc(sizeof *pM);

/* 1st test whether the allocation succeeded! */
if (NULL == pM)
{
  perror("malloc() failed");
  exit(EXIT_FAILURE);
}

/* Then initialise the array. */
for (size_t row = 0; row < ROWS_MAX; ++row)
{
  for (size_t column = 0; column < COLUMNS_MAX; ++column)
  {
    (*pM)[row][column] = 42;
  }
}

/* Do something ... */
...

/* Deallocate, free the memory. */
free(pM);

使用多个块或内存的替代方法是使用分散/稀疏数组:

unsigned long ** ppM = malloc(ROWS_MAX * sizeof *ppM);
if (NULL == ppM)
{
  perror("malloc() for row pointers failed");
  exit(EXIT_FAILURE);
}

for (size_t row = 0; row < ROWS_MAX; ++row)
{
  ppM[row] = malloc(COLUMNS_MAX * sizeof *ppM[row]);
  if (NULL == ppM[row])
  {
    perror("malloc() for a column failed");
    exit(EXIT_FAILURE);
    /* If not exiting the process here (but probably return from the function
       we are in), we need to perform a clean-up on what had been allocated 
       so far. See below code for free()ing it as a hint how to approach this. */
  }
}

/* Then initialise the array. */
for (size_t row = 0; row < ROWS_MAX; ++row)
{
  for (size_t column = 0; column < COLUMNS_MAX; ++column)
  {
    ppM[row][column] = 42; /* Note the difference how to access the array. */
  }
}

/* Do something ... */
...

/* Deallocate, free the memory. */
/* Free columns. */
for (size_t row = 0; row < ROWS_MAX; ++row)
{
  free(ppM[row]);
}

/* Free row pointers. */
free(ppM);