goodie2shoes
goodie2shoes

Reputation: 55

Program crashes when inserting values into large array C

I'm trying to do a homework assignment to measure the size of the L2 cache. I'm trying to create and fill a large array (too big for the cache) with random integers, which I'll then walk over in varying step sizes and benchmark the performance.

The problem I'm having is when I allocate memory for the large array and then start filling the array with random integers between 1 and 100, the program crashes (stack overflow?).

I'm very new to c programming unfortunately.

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

int main(int argc, char *argv[])
{
    int buffSize = sizeof(int) * 2000000;

    int * buff = (int*) malloc(buffSize);


    srand(time(NULL));

    for (int i = 0; i < buffSize; i++)
    {
        int r = rand() % 100 + 1;

        buff[i] = r;
    }

    return 0;
}

Upvotes: 0

Views: 429

Answers (2)

Spencer Rathbun
Spencer Rathbun

Reputation: 14910

You aren't creating a new array, you are allocating a block of memory based upon the size of int for your current architecture. You then proceed to treat it as an array, which works because of how c arrays and pointers work.

Once you do that, you start walking the array, but you have conflated the length of the array, with the size of the memory. If each int takes 4 bytes, then the size is 2000000 * 4 but the length is only 2000000. This is because each int you put into it takes 4 bytes, and so you can only fit size/4 worth of items into that space.

For what you want, just creating an array avoids malloc issues, and is more obvious:

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

int main(int argc, char *argv[])
{
    int arr_length = 2000000;
    int arr[arr_length];

    srand(time(NULL));

    for (int i = 0; i < arr_length; i++)
    {
        int r = rand() % 100 + 1;

        arr[i] = r;
    }

    return 0;
}

Upvotes: 0

cnicutar
cnicutar

Reputation: 182674

for (int i = 0; i < buffSize; i++)

You are going too far. You only need to go up until 2000000 while bufsize is 2000000 * sizeof(int).

Upvotes: 4

Related Questions