简体   繁体   English

矩阵乘法错误:分段错误(核心转储)

[英]Matrix multiplication error: Segmentation fault (core dumped)

I have the following code, and I want to calculate the running time of several matrix multiplications, with different sizes. 我有以下代码,我想计算几个不同大小的矩阵乘法的运行时间。 I started with matrix size of 100, and moved till 500, but when I try 1000, I get an error saying: Segmentation fault (core dumped), so I assume it has to do something with the memory. 我从矩阵大小100开始,一直移动到500,但是当我尝试1000时,我得到一个错误说:分段错误(核心转储),所以我认为它必须对内存做些什么。 I want to calculate the running time even of the matrices with sizes of 5000 and maybe 10000. Anyone can help me solve my problem? 我想计算大小为5000甚至10000的矩阵的运行时间。任何人都可以帮我解决我的问题?

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define SIZE 1000

int main(void)
{
    int A[SIZE][SIZE], B[SIZE][SIZE], C[SIZE][SIZE] = {0};
    int i, j, k;

    srand(time(NULL));

    for(i = 0; i < SIZE; i++)
    {
        for(j = 0; j < SIZE; j++)
        {
            A[i][j] = rand()%100;
            B[i][j] = rand()%100;
        }
    }

    clock_t begin, end;
    double time_spent;

    begin = clock();

    for(i = 0; i < SIZE; i++)
        for(j = 0; j < SIZE; j++)
            for(k = 0; k < SIZE; k++)
                C[i][j] += A[i][k] * B[k][j];

    end = clock();

    time_spent = (double)(end - begin) / CLOCKS_PER_SEC;

    printf("Elapsed time: %.2lf seconds.\n", time_spent);

    return 0;
}

This is a classic stack overflow - you have 3 local arrays each of approx 4 MB in size (assuming 32 bit ints) on your stack for a total of around 12 MB. 这是一个经典的堆栈溢出 - 你的堆栈上有3个本地阵列,大小约为4 MB(假设32位整数),总共大约12 MB。 On most modern operating systems the stack is typically 8 MB or less. 在大多数现代操作系统上,堆栈通常为8 MB或更少。 Either make the variables static, eg 要么使变量成为静态的,例如

static int A[SIZE][SIZE], B[SIZE][SIZE], C[SIZE][SIZE] = {0};

so that they no longer reside on the stack, or allocate them dynamically. 这样它们就不再驻留在堆栈上,也不会动态分配它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM