C for loop segmentation fault

二次信任 提交于 2019-12-11 06:55:58

问题


I am getting a segmentation fault error when I try to compile this code on gcc.

#include <stdio.h>
#include <stdlib.h>

#define N_TIMES     600000
#define ARRAY_SIZE   10000

int main (void)
{
    double  *array = calloc(ARRAY_SIZE, sizeof(double));
    double  sum = 0;
    int     i;

    double sum1 = 0;


    for (i = 0; i < N_TIMES; i++) {

        int     j;

        for (j = 0; j < ARRAY_SIZE; j += 20) {
            sum += array[j] + array[j+1] + array[j+2] + array[j+3] + array[j+4] + array[j+5] + array[j+6] + array[j+7] + array[j+8] + array[j+9];
            sum += array[j+10] + array[j+11] + array[j+12] + array[j+13] + array[j+14] + array[j+15] + array[j+16] + array[j+17] + array[j+18] + array[j+19];
            }
        }

    sum += sum1;

    return 0;
}

I'm trying to speed up a for loop as much as I can so I am trying crazy things. How do I get rid of the segmentation fault? Also should I try a different method of optimization?


回答1:


So your original problem was due to the fact that you were using i instead of j in your array index in the inner loop and since N_TIMES is much larger than ARRAY_SIZE you will end up overflowing your array bounds which is undefined behavior.

The corrected code still has one obvious problem:

sum += array[ARRAY_SIZE];

The valid indices for array will go from 0 to ARRAY_SIZE-1 so accessing element ARRAY_SIZE is invoking undefined behavior by going outside the array bounds.




回答2:


  1. The compiler will almost certainly optimize better than you. Don't try to outthink the compiler.

  2. Problem is almost certainly sum += array[ARRAY_SIZE]; Array indexes in C go from 0 to size-1, so here you are probably going "one off the end"



来源:https://stackoverflow.com/questions/18325131/c-for-loop-segmentation-fault

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!