I am trying to read the file's data into a dynamically declared array, using double *data = new double[14141414]()
declaration. Note, it is rather a large file; hence large size of an array.
The problem is I can not put all the data into an array as somewhere around index=14000000 the execution would just stop.
The code compiles just fine (no errors). I did debug and the new
returns an address, not 0 or NULL. So looks like there is no problem with memory allocation (ie running out of memory). I even echo-ed the file to screen without array assignment just to see that I am able to read through the file well. All looks good.
Yet, the moment I start putting data into an array, the program would just stop closer to the end but at random locations, Sometime it would be 14000000 sometimes the index would be a little bit more and sometimes a little bit less. There were couple times when the program ran well.
Does anybody know what is going on? I suspect the the computer running out of physical memory and hence this behavior of the program. But if this is so, then why does new
operator return an address? Should it return 0 or NULL if memory allocate fails?
Thanks!!
UPDATE: per #Jonathan Potter's request I am including the code here. Thanks!! Really good idea!!
void importData(){
int totalLineCount = 14141414;
double *height = new (nothrow) double[totalLineCount]();
int *weight = new (nothrow) int[totalLineCount]();
double *pulse = new (nothrow) double[totalLineCount]();
string *dateTime = new (nothrow) string[totalLineCount];
int *year = new (nothrow) int[totalLineCount]();
int *month = new (nothrow) int[totalLineCount]();
int *day = new (nothrow) int[totalLineCount]();
fstream dataFile(file.location.c_str(), ios::in);
for (int i = 0; i < totalLineCount; i++) {
dataFile >> weight[i]
>> height[i]
>> pulse[i]
>> year[i]
>> dateTime[i];
} //for
dataFile.close();
delete height;
delete weight;
delete pulse;
delete dateTime;
delete year;
delete month;
delete day;
}//function end
save yourself loads of trouble, use a
vector
vector will give you better debug messages and you won't have to deal with memory yourself.