I used the malloc
function for allocating 10^9 memory locations as part of an array.
The Code 1 gets executed successfully.
Code 1:
int main(){
int size = (int)(1e9);
int* arr = (int*) malloc( size * sizeof(int) );
for(int i=0;i<size;i++){
arr[i] = i;
}
return 0;
}
But when I tried to access the particular memory location or index value = 12345678 (which is < 1e9), I got segmentation fault
Code 2:
int main(){
int size = (int)(1e9);
int* arr = (int*) malloc( size * sizeof(int) );
for(int i=0;i<size;i++){
arr[i] = i;
}
cout<<arr[12345678]<<endl; //added this line of code, which gives segmentation fault
return 0;
}
My guess is, this occurs due to memory fragmentation, but I am not sure about this. Can anyone kindly explain the correct reason.