2016-11-10 4 views
1

私は動的に割り当てられた配列 "data"を持つ次のコードを持っています。コマンドライン引数として配列サイズを渡しています。プログラムはdatasize = 33790まで正常に動作します。値が33790より大きい場合、セグメント化エラーが発生します。セグメンテーションフォールト:大きな整数配列を動的に割り当てる

"33790"はマシン固有の可能性があります。動的に割り当てられたメモリが特定のサイズの後にseg faultを返す理由を理解しようとしています。どんな助けも歓迎です。 :)

#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; 
} 
+0

CはCではありません++はCではありません。無関係なタグを追加しないでください。 – Olaf

答えて

2

どのアレイを割り当てる(複数の要素を有する)が、一つだけint有する値datasizeを割り当てていません。

new int(datasize)の代わりにnew int[datasize]を使用して、datasize要素を持つintの配列を割り当てます。

+1

この回答があなたの問題を解決した場合は、それを正しいものとしてマークすることを検討してください。 –

関連する問題