c - Seg Fault when initializing array -
i'm taking class on c, , running segmentation fault. understand, seg faults supposed occur when you're accessing memory hasn't been allocated, or otherwise outside bounds. 'course i'm trying initialize array (though rather large @ that)
am misunderstanding how parse 2d array? misplacing bound cause seg fault-- wrong in using nested for-loop
this?
the professor provided clock functions, i'm hoping that's not problem. i'm running code in cygwin, problem? source code follows. using c99 standard well.
to clear: looking understanding (and fixing) reason code produces seg fault.
#include <stdio.h> #include <time.h> int main(void){ //first define array , 2 doubles count elapsed seconds. double rowmajor, colmajor; rowmajor = colmajor = 0; int majorarray [1000][1000] = {}; clock_t start, end; //set perform test 100 times. for(int k = 0; k<10; k++) { start=clock(); //first row major for(int = 0; < 1000; i++) { for(int j = 0; j<1000; j++) { majorarray[i][j] = 314; } } end=clock(); rowmajor+= (end-start)/(double)clocks_per_sec; //at point, we've done rowmajor, elapsed = rowmajor start=clock(); //now column major for(int = 0; < 1000; i++) { for(int j = 0; j<1000; j++) { majorarray[j][i] = 314; } } end=clock(); colmajor += (end-start)/(double)clocks_per_sec; } //now we've done calculations 100 times, can compare values. printf("row major took %f seconds\n", rowmajor); printf("column major took %f seconds\n", colmajor); if(rowmajor<colmajor) { printf("row major faster\n"); } else { printf("column major faster\n"); } return 0; }
your program works correctly on computer (x86-64/linux) suspect you're running system-specific limit on size of call stack. don't know how stack on cygwin, array 4,000,000 bytes (with 32-bit int
) - big.
try moving declaration of majorarray
out of main
(put right after #include
s) -- global variable, comes different allocation pool can bigger.
by way, comparison backwards:
if(rowmajor>colmajor) { printf("row major faster\n"); } else { printf("column major faster\n"); }
also, test ought repeat process many different array sizes , shapes.
Comments
Post a Comment