Defined in header <string.h>
   
  (1)  
char *strncpy( char *dest, const char *src, size_t count );
(until C99)
char *strncpy( char *restrict dest, const char *restrict src, size_t count );
(since C99)
errno_t strncpy_s(char *restrict dest, rsize_t destsz,
                  const char *restrict src, rsize_t count);
(2) (since C11)
     
1) Copies at most count characters of the character array pointed to by src (including the terminating null character, but not any of the characters that follow the null character) to character array pointed to by dest.
 If count is reached before the entire array src was copied, the resulting character array is not null-terminated.
 If, after copying the terminating null character from srccount is not reached, additional null characters are written to dest until the total of count characters have been written.
 The behavior is undefined if the character arrays overlap, if either dest or src is not a pointer to a character array (including if dest or src is a null pointer), if the size of the array pointed to by dest is less than count, or if the size of the array pointed to by src is less than count and it does not contain a null character.
2) Same as (1), except that the function does not continue writing zeroes into the destination array to pad up to count, it stops after writing the terminating null character (if there was no null in the source, it writes one at dest[count] and then stops). Also, the following errors are detected at runtime and call the currently installed constraint handler function:
  • src or dest is a null pointer
  • destsz or count is zero or greater than RSIZE_MAX
  • count is greater or equal destsz, but destsz is less or equal strnlen_s(src, count), in other words, truncation would occur
  • overlap would occur between the source and the destination strings
 The behavior is undefined if the size of the character array pointed to by dest < strnlen_s(src, destsz) <= destsz; in other words, an erroneous value of destsz does not expose the impending buffer overflow. The behavior is undefined if the size of the character array pointed to by src < strnlen_s(src, count) < destsz; in other words, an erroneous value of count does not expose the impending buffer overflow.
As with all bounds-checked functions, strncpy_s is only guaranteed to be available if __STDC_LIB_EXT1__ is defined by the implementation and if the user defines __STDC_WANT_LIB_EXT1__ to the integer constant 1 before including string.h.

Parameters

dest - pointer to the character array to copy to
src - pointer to the character array to copy from
count - maximum number of characters to copy
destsz - the size of the destination buffer

Return value

1) returns a copy of dest
2) returns zero on success, returns non-zero on error. Also, on error, writes zero to dest[0] (unless dest is a null pointer or destsz is zero or greater than RSIZE_MAX) and may clobber the rest of the destination array with unspecified values.

Notes

As corrected by the post-C11 DR 468, strncpy_s, unlike strcpy_s, is only allowed to clobber the remainder of the destination array if an error occurs.

Unlike strncpystrncpy_s does not pad the destination array with zeroes, This is a common source of errors when converting existing code to the bounds-checked version.

Although truncation to fit the destination buffer is a security risk and therefore a runtime constraints violation for strncpy_s, it is possible to get the truncating behavior by specifying count equal to the size of the destination array minus one: it will copy the first count bytes and append the null terminator as always: strncpy_s(dst, sizeof dst, src, (sizeof dst)-1);

Example

Run this code
#define __STDC_WANT_LIB_EXT1__ 1
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
 
int main(void)
{
char src[] = "hi";
char dest[6] = "abcdef"; // no null terminator
strncpy(dest, src, 5); // writes five characters 'h', 'i', '\0', '\0', '\0' to dest
printf("strncpy(dest, src, 5) to a 6-byte dest gives : ");
for(size_t n = 0; n < sizeof dest; ++n) {
char c = dest[n];
c ? printf("'%c' ", c) : printf("'\\0' ");
}
 
printf("\nstrncpy(dest2, src, 2) to a 2-byte dst gives : ");
char dest2[2];
strncpy(dest2, src, 2); // truncation: writes two characters 'h', 'i', to dest2
for(size_t n = 0; n < sizeof dest2; ++n) {
char c = dest2[n];
c ? printf("'%c' ", c) : printf("'\\0' ");
}
printf("\n");
 
#ifdef __STDC_LIB_EXT1__
set_constraint_handler_s(ignore_handler_s);
char dst1[6], src1[100] = "hello";
int r1 = strncpy_s(dst1, 6, src1, 100); // writes 0 to r1, 6 characters to dst1
printf("dst1 = \"%s\", r1 = %d\n", dst1,r1); // 'h','e','l','l','o','\0' to dst1
 
char dst2[5], src2[7] = {'g','o','o','d','b','y','e'};
int r2 = strncpy_s(dst2, 5, src2, 7); // copy overflows the destination array
printf("dst2 = \"%s\", r2 = %d\n", dst2,r2); // writes nonzero to r2,'\0' to dst2[0]
 
char dst3[5];
int r3 = strncpy_s(dst3, 5, src2, 4); // writes 0 to r3, 5 characters to dst3
printf("dst3 = \"%s\", r3 = %d\n", dst3,r3); // 'g', 'o', 'o', 'd', '\0' to dst3
#endif
}

Possible output:

strncpy(dest, src, 5) to a 6-byte dst gives : 'h' 'i' '\0' '\0' '\0' 'f'
strncpy(dest2, src, 2) to a 2-byte dst gives : 'h' 'i'
dst1 = "hello", r1 = 0
dst2 = "", r2 = 22
dst3 = "good", r3 = 0

References

  • C11 standard (ISO/IEC 9899:2011):
  • 7.24.2.4 The strncpy function (p: 363-364)
  • K.3.7.1.4 The strncpy_s function (p: 616-617)
  • C99 standard (ISO/IEC 9899:1999):
  • 7.21.2.4 The strncpy function (p: 326-327)
  • C89/C90 standard (ISO/IEC 9899:1990):
  • 4.11.2.4 The strncpy function

From: https://en.cppreference.com/w/c/string/byte/strncpy

strncpy, strncpy_s的更多相关文章

  1. c/c++头文件_string

    string, cstring, string.h 一.string头文件 主要包含一些字符串转换的函数 // sto* NARROW CONVERSIONS// sto* WIDE CONVERSI ...

  2. 字符串操作函数<string.h>相关函数strcpy,strcat,等源码。

    首先说一下源码到底在哪里找. 我们在文件中包含<cstring>时,如果点击右键打开文档, 会打开cstring,我们会发现路径为: D:\Program Files\visual stu ...

  3. strcpy、strncpy 和安全的strncpy_s

    strcpy和strncpy摘于linux 内核源码的/lib/string.c char *self_strcpy(char *dest, const char *src) { char *tmp ...

  4. C语言strcpy,strncpy和strlcpy讲解

    前言 C风格的字符串处理函数有很多,如strcpy().strcat()等等. strcpy与strcat char* strcpy (char* dest, const char* src); ch ...

  5. strcpy/strncpy/strcpy_s比较

    转载自:http://blog.csdn.net/caomiao2006/article/details/4766416 strcpy()是依据源串的/0作为结束判断的,不检查copy先的Buffer ...

  6. strncpy函数使用

    strncpy()函数原型:extern char *strncpy(char *dest, char *src, int n);    用法:#include <string.h>    ...

  7. Linux C 字符串函数 strlen()、strcat()、strncat()、strcmp()、strncmp()、strcpy()、strncpy() 详解

      strlen(返回字符串长度) 表头文件 #include <string.h> 定义函数 size_t strlen(const char *s); 函数说明 strlen()用来计 ...

  8. strncpy,strcpy

    strncpy不会为des自动添加“\0” strcpy遇空结束,自动添加结束符 结论: 1.使用strcpy时一定不能用于无结束符的字符串,因为strcpy依赖\0判断源字符串的结束 2.使用str ...

  9. [skill] strncpy里边有两个坑

    以前的笔记,今日翻出了复看了一下,转过来. ------------------------------------ 今天发现xxxdump中使用xxx_strncpy 替换 strncpy导致的bu ...

随机推荐

  1. python3实现链表

    1.链表的实现 a.链表的结构为: b.链表的实现方法; #链表结构实现 私有属性_pro_item是指向下个节点的指针,_item为此节点的值 class ChainDemo(): def __in ...

  2. 005 Numpy的基本操作

    一:数组与标量,数组与数组之间的运算 1.数组与标量之间的计算 2.数组之间的加减乘除 3.元素级运算 二:.矩阵积 1.说明 这个的意思是第一个数组的列,必须和第二个数组的行的大小相同 2.运算 3 ...

  3. Mysql 查询实现成绩排名

    Mysql 查询实现成绩排名,相同分数名次相同,类似于rank()函数 近日系统要实现总分成绩排名,而且相同分数的学生排名要一样,在网上搜了一圈,没有找到合适的方法,只能靠自己实现了,这里提供两种方法 ...

  4. 2018年中国研究生数学建模竞赛C题 二等奖 赛题论文

    2018年中国研究生数学建模竞赛C题 对恐怖袭击事件记录数据的量化分析 恐怖袭击是指极端分子或组织人为制造的.针对但不仅限于平民及民用设施的.不符合国际道义的攻击行为,它不仅具有极大的杀伤性与破坏力, ...

  5. 线段树-hdu3397

    题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=3397 题目描述: 题目大意:给我们一串二进制串,需要我们对其进行以下操作: 1.输入0,a,b,将a, ...

  6. 【python】进程与线程

    No1: 多进程 from multiprocessing import Process import os # 子进程要执行的代码 def run_proc(name): print('Run ch ...

  7. Nightmare Ⅱ HDU - 3085 (双向bfs)

    Last night, little erriyue had a horrible nightmare. He dreamed that he and his girl friend were tra ...

  8. 最长不下降子序列nlogn

    b[i]表示长度为i的最长不下降子序列的最小末尾元素的值显然它是单调递增的,满足二分性质,然后就可以愉快地二分啦. #include<iostream> #include<cstdi ...

  9. SparkException: Could not find CoarseGrainedScheduler or it has been stopped.

    org.apache.spark.SparkException: Could not find CoarseGrainedScheduler or it has been stopped. at or ...

  10. 页面中去除浮动 clear:both

    今天写代码发现一个很奇怪的问题,发现上面的div加浮动(不管是否包含div)以后对下面div的浮动有所影响,通过去除浮动,搞定: 只需要在受影响的div中的样式中,加入clear:both即可