Ali Mohyudin
Ali Mohyudin

Reputation: 242

Why is strncpy marked as unsafe?

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));

Upvotes: 6

Views: 7801

Answers (3)

Yakk - Adam Nevraumont
Yakk - Adam Nevraumont

Reputation: 275405

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.

Upvotes: 9

Stefano Falsetto
Stefano Falsetto

Reputation: 572

The "n" variants of str functions (like strncmp, strncpy, etc) are the "safe" choice, because they all are limiting the size of string buffer used. The "old" str functions (not the "n" variants, like strcpy) are all subject to many programming errors and memory attacks (off by one, heap overwriting, etc).

Upvotes: -1

mantal
mantal

Reputation: 1209

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).

Upvotes: 4

Related Questions