c - what causes segmentation fault in below program -


this question has answer here:

if keep value of rows 100000, program works fine, if make rows 1 million 1000000, program gives me segmentation fault. reason? 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 local variable inside main function. "allocated" on machine call stack.

this stack has limits.

you should make matrix global or static variable or make pointer , heap-allocate (with e.g. calloc or malloc) memory zone. don't forget calloc or malloc may fail (by returning null).

a better reason heap-allocate such thing dimensions of matrix should variable or input. there few reasons wire-in dimensions in source code.

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

[of course, there valid exceptions heuristic]


Comments

Popular posts from this blog

how to insert data php javascript mysql with multiple array session 2 -

multithreading - Exception in Application constructor -

windows - CertCreateCertificateContext returns CRYPT_E_ASN1_BADTAG / 8009310b -