5

I am trying to understand the effects of caching programmatically using the following program. I am getting segfault with the code. I used GDB (compiled with -g -O0) and found that it was segmentation faulting on

start = clock() (first occourance)

Am I doing something wrong? The code looks fine to me. Can someone point out the mistake?

#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;
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
liv2hak
  • 14,472
  • 53
  • 157
  • 270

2 Answers2

8

The array might be too big for the stack. Try making it static instead, so it goes into the global variable space. As an added bonus, static variables are initialized to all zero.

Unlike other kinds of storage, the compiler can check that resources exist for globals at compile time (and the OS can double check at runtime before the program starts) so you don't need to handle out of memory errors. An uninitialized array won't make your executable file bigger.

This is an unfortunate rough edge of the way the stack works. It lives in a fixed-size buffer, set by the program executable's configuration according to the operating system, but its actual size is seldom checked against the available space.

Welcome to Stack Overflow land!

Potatoswatter
  • 134,909
  • 25
  • 265
  • 421
4

Try to change:

int arr[MAX_SIZE];

to:

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

As Potatoswatter suggested The array might be too big for the stack... You might allocate on the heap, than on the stack...

More informations.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Gauthier Boaglio
  • 10,054
  • 5
  • 48
  • 85