I'm getting this error when I execute the following function and I have no idea what it means. Here is the function:
void readf2()
{
std::ifstream inFile("f2",std::ios_base::binary);
std::string str(2, '\0');
int i = 0;
while(inFile.read(&str[i],2)){
cout<<"Success: ["<< i << "] = "<< (int)str[i]; ;
cout<<"\n";
i++;
}
}
The function works for a while writing various numbers to the console and then boom it crashes with this error, a backtrace, and a memory map. Is this happening because I am freeing a memory address that doesn't exist?
Most likely you're giving the read
call a pointer to memory that doesn't belong to you.
str[i]
returns an offset in the string, but it doesn't guarantee that you have enough memory to read to that location (+2).
What you probably meant was to have an array of int
s, and use the i
as an index on that:
void readf2()
{
std::ifstream inFile("f2",std::ios_base::binary);
std::vector< int > str; // if you're reading int's - use int, not string
int i = 0;
int j;
while(inFile.read(&j,sizeof(int))){ // check what the content is here
str.push_back(j);
cout<<"Success: ["<< i << "] = "<< str[i];
cout<<"\n";
i++;
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.