调用clock()时出现分段错误

liv*_*hak 5 c linux performance

我试图使用以下程序以编程方式了解缓存的影响.我正在使用代码获得段错误.我使用GDB(编译-g -O0),发现它是分段错误

start = clock() (first occourance)
Run Code Online (Sandbox Code Playgroud)

难道我做错了什么?代码看起来很好.有人可以指出错误吗?

#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;
}
Run Code Online (Sandbox Code Playgroud)

Pot*_*ter 8

数组可能对于堆栈来说太大了.尝试static改为,所以它进入全局变量空间.作为额外的奖励,static变量被初始化为全零.

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

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

欢迎来到Stack Overflow土地!


Gau*_*lio 4

尝试改变:

int arr[MAX_SIZE];
Run Code Online (Sandbox Code Playgroud)

到:

int *arr = (int*)malloc(MAX_SIZE * sizeof(int));
Run Code Online (Sandbox Code Playgroud)

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

更多信息