So I created this program to write vectors of integer into a binary file, then retrieve the data again back.
//vec.cpp
#include <iostream>
#include <vector>
#include <fstream>
template<typename T>
void writeKey(std::string filename, std::vector<T> arr)
{
arr.insert(arr.begin(),(T)arr.size());
std::ofstream write_bin(filename, std::ios::out | std::ios::binary);
if(!write_bin)
{
std::cout << "ERROR: writing vector to file!\n";
exit(1);
}
for(size_t i = 0; i < arr.size(); i++)
{
write_bin.write((char *) &arr[i], sizeof(int));
}
write_bin.close();
if(!write_bin.good())
{
std::cout<<"ERROR: writing time error\n";
exit(1);
}
}
template<typename T>
std::vector<T> readKey(std::string filename)
{
std::ifstream read_bin(filename, std::ios::out | std::ios::binary);
if(!read_bin)
{
std::cout<<"ERROR: reading binary file!\n";
exit(1);
}
size_t limit;
read_bin.read((char*)&limit, sizeof(T));
std::cout<<"limit : "<<limit<<'\n';
std::vector<T> arr(limit,0);
for(size_t i=0; i<limit; ++i)
{
read_bin.read((char*)&arr[i], sizeof(T));
}
read_bin.close();
return arr;
}
int main()
{
std::vector<int> mykey = {5,10,15,20};
writeKey("test.key", mykey);
std::vector<int> mykeys = readKey<int>("test.key");
for(auto e: mykeys)
std::cout<<e<<' ';
std::cout<<'\n';
return 0;
}
So you see what I did here is I compile the program that only call the writeKey() function then run it... The program it runs perfectly
int main()
{
std::vector<int> mykey = {5,10,15,20};
writeKey("test.key", mykey);
return 0;
}
Then I compiled it again but this time I only call the readkey() function, then I run it, and again it runs as intended
int main()
{
std::vector<int> mykeys = readKey<int>("test.key");
for(auto e: mykeys)
std::cout<<e<<' ';
std::cout<<'\n';
return 0;
}
The problem arises the moment I call these two function inside the main() function, then compile and run it here the limit variable in readkey function is having some kind of overflowed value instead of the value that I inserted at the begining of the vector in the writekey function
int main()
{
std::vector<int> mykey = {5,10,15,20};
writeKey("test.key", mykey);
std::vector<int> mykeys = readKey<int>("test.key");
for(auto e: mykeys)
std::cout<<e<<' ';
std::cout<<'\n';
return 0;
}
What is happening here? and how can I fix this?
this is my compilation flags : g++ -o vec.o vec.cpp -Wall -Wextra -fsanitize=address