1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Dec 2012
    Rep Power

    Problem with short program

    This is my first time writing in C and I'm trying to compile and run a program in C that is supposedly standard code for dense matrix multiplication. However i'm getting this segmentation fault (core dumped) error and i have no idea what the problem is. Here is my code:

    int main(){

    int N = 1024;
    int x[N][N];
    int y[N][N];
    int z[N][N];
    int i;
    int r;
    int k;
    int j;

    for (i = 0; i < N; i = i+1) {
    for (j = 0; j < N; j = j+1)
    {r = 0;
    for (k = 0; k < N; k = k+1){
    r = r + y[i][k]*z[k][j];};
    x[i][j] = r;

    return 0;
  2. #2
  3. Contributed User
    Devshed Specialist (4000 - 4499 posts)

    Join Date
    Jun 2005
    Rep Power
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper
  4. #3
  5. Banned ;)
    Devshed Supreme Being (6500+ posts)

    Join Date
    Nov 2001
    Woodland Hills, Los Angeles County, California, USA
    Rep Power
    Since you said you got a Segfault and a core file, I'll assume you're running on a Linux system. It looks like you've got a stack-smashing issue (basically, you're allocating too much data on the stack). For instance,
    int N = 1024;
    int x[N][N];
    Assuming an int is 4 bytes, we have 1024 * 1024 * 4 = 4 MB just for this one array. Now you have 3 such arrays declared x, y and z. Therefore total stack needed for just these three arrays is 4 * 3 = 12 MB. And we also need stack space for the remaining variables as well (i, j, k, r) as well as for function calls. So we'll need stack somewhat more than 12 MB to run this program.

    Now if you go to your linux system and type:
    ulimit -s
    This shows the max. amount of stack assigned to your programs by default. On my system, it says:
    mb@motorhead:~$ ulimit -s
    i.e. 8MB max. stack is allocated to my program when it starts up. This is less than the min. of 12 MB+ stack that the program needs.

    Now if I change the max. amount to something else (such as 16384 (i.e.) 16 MB), the code runs without segfault.
    mb@motorhead:~/cpp$ ./matrix 
    Segmentation fault
    mb@motorhead:~/cpp$ ulimit -s 16384
    mb@motorhead:~/cpp$ ./matrix
    .... runs all the way without segfault ....
    Of course the result will be nonsense, since you haven't set y or z, but I'll assume you knew that already.
    Hope this helps.
    Up the Irons
    What Would Jimi Do? Smash amps. Burn guitar. Take the groupies home.
    "Death Before Dishonour, my Friends!!" - Bruce D ickinson, Iron Maiden Aug 20, 2005 @ OzzFest
    Down with Sharon Osbourne

    "I wouldn't hire a butcher to fix my car. I also wouldn't hire a marketing firm to build my website." - Nilpo

IMN logo majestic logo threadwatch logo seochat tools logo