【问题标题】:Segmentation fault when calling clock()调用clock()时出现分段错误
【发布时间】:2013-06-12 20:38:03
【问题描述】:

我正在尝试使用以下程序以编程方式了解缓存的效果。我的代码出现段错误。我使用了 GDB(用-g -O0 编译),发现它是分段错误的

start = clock() (first occourance)

我做错了吗?代码对我来说看起来不错。有人能指出错误吗?

#include <stdio.h>
#include <sys/time.h>
#include <time.h>
#include <unistd.h>

#define MAX_SIZE (16*1024*1024)
int main()
{
    clock_t start, end;
    double cpu_time;
    int i = 0;
    int arr[MAX_SIZE];

    /* CPU clock ticks count start */
    start = clock();

    /* Loop 1 */
    for (i = 0; i < MAX_SIZE; i++) 
        arr[i] *= 3;

    /* CPU clock ticks count stop */
    end = clock();

    cpu_time = ((double) (end - start)) / CLOCKS_PER_SEC;

    printf("CPU time for loop 1 %.6f secs.\n", cpu_time);

    /* CPU clock ticks count start */
    start = clock();

    /* Loop 2 */
    for (i = 0; i < MAX_SIZE; i += 16) 
        arr[i] *= 3;

    /* CPU clock ticks count stop */
    end = clock();

    cpu_time = ((double) (end - start)) / CLOCKS_PER_SEC;

    printf("CPU time for loop 2 %.6f secs.\n", cpu_time);

    return 0;
}

【问题讨论】:

    标签: c linux performance


    【解决方案1】:

    数组对于堆栈来说可能太大了。试着改成static,让它进入全局变量空间。另外,static 变量被初始化为全零。

    与其他类型的存储不同,编译器可以在编译时检查全局资源是否存在(操作系统可以在程序启动之前在运行时进行双重检查),因此您无需处理内存不足错误。未初始化的数组不会使您的可执行文件变大。

    这是堆栈工作方式的不幸边缘。它位于一个固定大小的缓冲区中,由程序可执行文件的配置根据操作系统设置,但很少根据可用空间检查其实际大小。

    欢迎来到 Stack Overflow 的土地!

    【讨论】:

      【解决方案2】:

      尝试改变:

      int arr[MAX_SIZE];
      

      到:

      int *arr = (int*)malloc(MAX_SIZE * sizeof(int));
      

      正如 Potatoswatter 建议的 The array might be too big for the stack...您可能在堆上分配,而不是在堆栈上...

      More informations.

      【讨论】:

        猜你喜欢
        • 2018-03-17
        • 2017-08-05
        • 2015-10-03
        • 2018-05-15
        • 2019-04-20
        • 2015-10-02
        • 2019-07-25
        相关资源
        最近更新 更多