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

标签 c linux memory allocation

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

unsigned long M[2000][900000] ;

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

enter image description here

Processus arrêté (Process stopped)  

最佳答案

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);

使用多个 block 或内存的另一种方法是使用分散/稀疏数组:

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);

关于c - 如何在linux中使用C分配大数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36809741/

相关文章:

c - C的内存泄漏检测器?

c - 如何从文件中逐行读取

c - C中结构的动态分配

java - 因果关系示例执行

c++ - 为什么在下面的代码中将内存分配给 *p

c - 在c中的结构中使用union的目的

c - 运行程序的多个输入

linux - sed : printing lines between two words only when one of the line matches a third word or any pattern

linux - 关于linux程序内存布局schema的问题

MySQL 5.1 内存表