ITeye博客

使用strncpy_s 比 使用strncpy更加安全

futrueboy · 2008-09-14 10:29 · Markdown

以下使用strncpy 但不安全

#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 我们认为它更安全

#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;
}

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。