Hi all,
I'm having problems writing to a file, and can't figure out what's happening.
Basically I have a program which tracks movement over several timeunits (each timeunit takes several timesteps). At each timeunit I write the results to a .txt file. However my program keeps crashing on the last timeunit when trying to write to file and I can't figure out why. It manages to write to the file on each other timestep (no matter how many I put in), with the correct file name e.g. "Map_time_0.txt", but not the last.
I thought this might be an indexing problem, but I can't see any reason why changing the time value will cause this to crash.
Gives this error:
Unhandled exception at 0x7c812afb in Puccinia striiformis.exe: Microsoft C++ exception: std::bad_alloc at memory location 0x0012fb04..
This is a summary of the writing parts of my code:
// I'm not entirely sure all these headers are relevant here, but thought
// I'd better include them just incase.
#include <sstream>
#include <fstream>
#include <iostream>
#include <iomanip>
#include <stdio.h>
int main(void)
{
int TIMEUNITS=4;
int TIMESTEPS=2;
int Time=0;
while(Exit_flag!=1){
// Each timeunit...
if((Time%TIMESTEPS)==0){
// Update the proportion infected per bin
Update_records(Time);
// Write coordinates and severity to a file.
Write_maps(Time);
}
// Check for infection, and then change states of relevant plants
Timestep();
Time++;
// Check whether to EXIT or not
Check_exit();
}
Write_maps(Time);
}
And the functions:
void Check_exit(){
if(Time>=TIMESTEPS*TIMEUNITS) Exit_flag=1;
else Exit_flag=0;
}
void Write_maps(int Time){
std::string file_name, cTime;
std::cout << Time << std::endl;
std::stringstream ssFileName;
ssFileName << "Map_time_";
ssFileName << (int)Time/TIMESTEPS;
ssFileName << ".txt";
std::cout << ssFileName.str() << std::endl;
file_name = ssFileName.str();
std::cout << "File name = " << file_name <<std::endl;
std::ofstream myfile( file_name.c_str() );
// Print out results
for(int i=0;i<NO_OF_PLANTS;i++){
myfile << plants[i].X_coord << "," << plants[i].Y_coord << "," << plants[i].severity() << std::endl;
}
myfile.close();
}
The program manages to print out the File name = ..., and then seems to crash when trying to create the myfile ofstream object.
Any help would be appreciated.