Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is strncpy marked as unsafe?

Tags:

c++

I am getting a warning:

warning C4996: 'strncpy': This function or variable may be unsafe. Consider using  strncpy_s instead.
To disable deprecation, use _CRT_SECURE_NO_WARNINGS. See online help for details.
F:\vuStudio\VC\include\string.h(188) : see declaration of 'strncpy'

I read on stackoverflow.com that strcpy is not safe and I should use strncpy instead. But now why I am getting warning that strncpy is unsafe ?

I am calling it as:

strncpy(this->title, title.c_str(), sizeof(this->title));
like image 271
Ali Mohyudin Avatar asked Sep 09 '14 13:09

Ali Mohyudin


2 Answers

strncpy has a few dangerous quirks.

First, it zeros the target buffer past the end of the copy, which can be surprising.

Second, if there is not enough room in the target buffer, it does not null terminate the target buffer.

Third, if it truncates, it 'mostly works'. Which discourages error handling (truncated strings are often worse than useless, but do not appear to be worse than useless at first glance).

strncpy_s requires an input length (or explicit truncation request), and errors if there is not enough room to null terminate (writing just a zero length string in the output). The input length is sometimes inefficient to provide (and not required for some of its changes), but it does guarantee a null terminated output buffer (so long as it isn't a nullptr, or zero length) even in error conditions. I am unsure if it zeros past the end of the copied string or not.

This behavior prevents or mitigates some common fenceposting errors in string code.

like image 106
Yakk - Adam Nevraumont Avatar answered Nov 15 '22 22:11

Yakk - Adam Nevraumont


Visual studio compiler has it's own implementation of strncpy, you won't get this warning with gcc or clang. It is safe, and more portable (because strncpy_s is not standard) to use strncpy.

If you don't care about portability, strncpy_s is indeed more secure because it has an additional length check (but like strncpy it won't save you if you pass bad parameter).

like image 37
mantal Avatar answered Nov 15 '22 22:11

mantal