Re: std::copy unsafe error
On 6/24/2014 4:04 PM, Christopher Pisz wrote:
On 6/24/2014 12:14 PM, Victor Bazarov wrote:
On 6/24/2014 12:41 PM, Christopher Pisz wrote:
I am getting an error from std::copy_impl about this being unsafe. Is
there an alternative I can use? Or am I using it incorrectly here? I am
not sure why this would be "unsafe."
void Foo(const std::wstring & text)
{
// Double NULL required at end
wchar_t * buffer = new wchar_t[fullyQualifiedPath.size() + 2];
std::copy(fullyQualifiedPath.begin(), fullyQualifiedPath.end(),
buffer);
buffer[fullyQualifiedPath.size() ] = L'\0';
buffer[fullyQualifiedPath.size() + 1] = L'\0';
// SNIP
}
Not enough information. How is 'fullyQualifiedPath' declared? Also,
consider that you actually don't need to do the .size()] = 0 if you
zero-initialize it using the parentheses:
... buffer = new ... + 2]();
What's "std::copy_impl" and how are you "getting an error" from it about
your code "being unsafe"? Be more verbose. Is this a compiler error?
Then provide the compiler output. Is it a run-time error? Then provide
the output of your program.
Is this your first day in c.l.c++?
V
Full listing:
#include <string>
#include <algorithm>
void Foo(const std::wstring & text)
{
// Double NULL required at end
wchar_t * buffer = new wchar_t[text.size() + 2];
std::copy(text.begin(), text.end(), buffer);
buffer[text.size() ] = L'\0';
buffer[text.size() + 1] = L'\0';
// SNIP
}
int main()
{
std::wstring text = L"blahdedeblahblah";
return 0;
}
MSVC11.0 gives compiler error:
Error 1 error C4996: 'std::_Copy_impl': 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' c:\program files (x86)\microsoft visual studio
11.0\vc\include\xutility 2176 Test
Well, actually it's a warning (which you perhaps decided to treat as an
error), and you can disable it. There are at least three ways I know
that warning can be disabled, but all of them are compiler-specific, and
as such off-topic here. Read the compiler error/warning message and pay
more attention to the instructions, perhaps you will think of a way...
I am asking why the compiler believes it to be unsafe, if it is indeed
unsafe, or if there an alternative way I should be using.
It is indeed unsafe. You're passing a naked pointer as the destination,
and if you forgot to allocate enough room in the destination, the buffer
can be overrun, which is unsafe (and known to be a method to breach
security.)
You could be using a vector (along with 'back_inserter') as the
destination, which is safer, of course.
I imagine std::copy_impl is microsoft's implementation of std::copy, but
who knows.
Yes, well, as soon as you switch to building 'Release', that warning is
going away, so...
V
--
I do not respond to top-posted replies, please don't ask