且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

是什么原因导致分段故障在下面的程序

更新时间:2022-10-19 14:09:07

矩阵里面一个局部变量的功能。因此,它是本机调用堆栈上的分配。

这堆有一些限制。

您应该让您的矩阵全局或静态变量或使其指针和堆分配(以例如:释放calloc 的malloc )的存储区。不要忘记,释放calloc 的malloc 可能会失败(通过返回NULL)。

有一个更好的理由来堆分配这样的事情是矩阵的尺寸确实应该是一个变量或某些输入。有接线,在源$ C ​​$ C尺寸几个原因。

启发式:没有一个本地帧(局部变量'大小的累计总和)超过一个或两个千字节更大。

[当然,也有例外的有效向启发式]

If i keep the value of rows to 100000, the program works fine, but if i make rows one million as 1000000, the program gives me segmentation fault. What is the reason? I am running below on linux 2.6x RHEL kernel.

#include<stdio.h>

#define ROWS 1000000
#define COLS 4

int main(int args, char ** argv)
{
  int matrix[ROWS][COLS];

  for(int col=0;col<COLS;col++)
  for(int row=0;row < ROWS; row++)
    matrix[row][col] = row*col;

  return 0;
}

The matrix is a local variable inside your main function. So it is "allocated" on the machine call stack.

This stack has some limits.

You should make your matrix a global or static variable or make it a pointer and heap-allocate (with e.g. calloc or malloc) the memory zone. Don't forget that calloc or malloc may fail (by returning NULL).

A better reason to heap-allocate such a thing is that the dimensions of the matrix should really be a variable or some input. There are few reasons to wire-in the dimensions in the source code.

Heuristic: don't have a local frame (cumulated sum of local variables' sizes) bigger than a kilobyte or two.

[of course, there are valid exceptions to that heuristic]