1

I have following code with one dynamically allocated array "data". I am passing array size as a command line argument. The program works fine until datasize = 33790. It gives segmentation fault if I try to provide a value > 33790.

"33790" might be machine specific. I am trying to understand why a dynamically allocated memory would return seg fault after a particular size. Any help is welcome. :)

#include "iostream"
#include <stdlib.h>
#include "iomanip"
#include "ctime"

#define N 100000

using namespace std;

int main(int argc, char* argv[])
{
    int a;
    cout<<"Size of int : "<<sizeof(int)<<endl;

    long int datasize = strtol(argv[1],NULL,0);
    cout<<"arg1 : "<<datasize<<endl;
    double sum = 0;
    int *data;
    data = new int(datasize);

    clock_t begin = clock();
    for(int i = 0; i < N; i++)                              //repeat the inner loop N times
    {
        //fetch the data into the cache
        //access it multiple times in order to amortize the compulsory miss latency
        for (long int j = 0; j < datasize; j++)
        {
            sum += data[j];                                 //get entire array of data inside cache
        }
    }

    clock_t end = clock();

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

    cout<<"sum = "<<sum<<endl;
    cout<<"Time Spent for data size = "<<argv[1]<<" is "<<time_spent<<endl;

    delete[] data;

    return 0;
}
1
  • C is not C++ is not C. Don't add unrelated tags. Commented Nov 10, 2016 at 0:57

1 Answer 1

2

You are not allocating any arrays (having multiple elements) but allocating only one int having value datasize.

Use new int[datasize] instead of new int(datasize) to allocate an array of int having datasize elements.

Sign up to request clarification or add additional context in comments.

1 Comment

If this answer solved your problem, consider marking it as correct.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.