---
title: "使用strncpy_s 比 使用strncpy更加安全"
author: "futrueboy"
date: "2008-09-14T10:29:14Z"
tags: []
slug: "strncpy-s-strncpy"
draft: false
lastmod: "2008-09-14T10:29:14Z"
id: 241556
url: "https://futrueboy.iteye.com/blog/241556"
---

以下使用strncpy 但不安全

```c++
#include <stdio.h>
#include <malloc.h>
#include <string.h>
#include <windows.h>

int main (int argc, char *argv[])
{
	char *p = "hello who you are ? ";
	char *dest;
	char s[20];
	int valLen;
	
	dest = (char *) malloc (sizeof (char) * 1000);

	//if we use strncpy_s we will get assert
	//for the size is not enough
	//we can just change s[20] to s[21]
	/*
	strncpy_s(s, _countof(s), p, strlen(p));
	printf("%s\n", s);
	*/


    // Here we use strncpy and get null termination
	strncpy (dest, p, (valLen = strlen(p)));
	dest[vallen] = '\0';
	printf ("%s\n", dest);

	//system ("pause");
	return 0;
}
```

以下用strncpy 我们认为它更安全

```c++
#include <stdio.h>
#include <malloc.h>
#include <string.h>
#include <windows.h>

int main (int argc, char *argv[])
{
	char *p = "hello who you are ? ";
	char *dest;
	char s[20];
	int valLen;
	
	dest = (char *) malloc (sizeof (char) * 1000);

	//if we use strncpy_s we will get assert
	//for the size is not enough
	//we can just change s[20] to s[21]
   	
	strncpy_s(s, _countof(s), p, strlen(p));
	printf("%s\n", s);
	


    // Here we use strncpy and get null termination
         /*
	strncpy (dest, p, (valLen = strlen(p)));
	dest[vallen] = '\0';
	printf ("%s\n", dest);
         */
	//system ("pause");
	return 0;
}
```