[英]Segmentation Fault: Dynamically allocating large integer array
我有一個帶有動態分配的數組“數據”的以下代碼。 我將數組大小作為命令行參數傳遞。 該程序可以正常工作,直到datasize =33790。如果我嘗試提供一個大於33790的值,它將產生分段錯誤。
“ 33790”可能是特定於計算機的。 我試圖了解為什么動態分配的內存在特定大小后會返回段錯誤。 歡迎任何幫助。 :)
#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;
}
您不分配任何數組(具有多個元素),而是僅分配一個具有值datasize
int
。
使用new int[datasize]
而不是new int(datasize)
分配具有datasize
元素的int
數組。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.