Reputation: 254926
Disclaimer: it's just another task for beginner so I'm good with the fact that on different compilers and on different architectures I may get different (incompatible) binaries as a result. So it's ok that it will only work only on this particular machine.
I'm writing and reading size_t
from a binary file. Writing looks like:
std::string result;
result.append((char *)&block_size_, sizeof(block_size_));
and soon after that result
is written to a file.
But when I read it in a same way:
map_binary.copy((char *)&block_size_, sizeof(block_size_), offset);
I get a warning
warning C4996: 'std::basic_string<_Elem,_Traits,_Alloc>::copy': Function call with parameters that may be unsafe - this call relies on the caller to check that the passed values are correct. To disable this warning, use -D_SCL_SECURE_NO_WARNINGS. See documentation on how to use Visual C++ 'Checked Iterators'
1> with
1> [
1> _Elem=char,
1> _Traits=std::char_traits<char>,
1> _Alloc=std::allocator<char>
1> ]
1> c:\program files (x86)\microsoft visual studio 11.0\vc\include\xstring(1777) : see declaration of 'std::basic_string<_Elem,_Traits,_Alloc>::copy'
1> with
1> [
1> _Elem=char,
1> _Traits=std::char_traits<char>,
1> _Alloc=std::allocator<char>
1> ]
I cannot get why this code is unsafe and looking for a solution other than pretending there is no issues at all (using the -D_SCL_SECURE_NO_WARNINGS
).
So, what am I missing?
PS: right now I'm learning C++ using only standard library, so solutions that use boost
or something else are unacceptable.
Upvotes: 2
Views: 1365
Reputation: 8027
You're not missing anything. VC++ is very keen to warn you if you copy anything to a pointer. In this case there is no guarantee that you will get the size of destination correct. After all you might write something like this map_binary.copy((char *)&block_size_, 4, offset);
and then find your code fails with a 64-bit compiler.
If you're happy with your ability to avoid this kind of error then disable or ignore the warning.
Upvotes: 1