1
我有一個動態分配的數組「數據」下面的代碼。我將數組大小作爲命令行參數傳遞。該程序工作正常,直到datasize = 33790.如果我嘗試提供大於33790的值,則會給出分段錯誤。分段錯誤:動態分配大整數數組
「33790」可能是機器特定的。我想了解爲什麼動態分配的內存在特定大小後會返回seg故障。歡迎任何幫助。 :)
#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;
}
C不是C++不是C.不要添加不相關的標籤。 – Olaf