strncpy和snprintf在拷贝字符串时的区别与利弊分析

本文探讨了strncpy和snprintf在复制字符串时的行为差异。strncpy总是拷贝指定数量的字符,可能导致非字符串数据的错误拷贝,而snprintf在拷贝后会确保添加,即使源字符串小于指定大小,也能保证目标字符串的正确性。通过三个实验对比,展示了两种函数在不同场景下的表现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 首先说结论

strncpy:无论src是否是一个字符串,带不带\0,都拷贝n个字符到dest

snprintf:最多拷贝size-1个字符到str,并在结尾加上\0,如果src不够size的大小,那么只拷贝src的长度,并在结尾加上\0

以下是做的实验

#include <string.h> 
#include <stdio.h> 
#include <stdarg.h> 
#include <stdlib.h>
#include <time.h> 
#include <ctype.h> 
#include <unistd.h>
#include <fcntl.h> 
#include <sys/stat.h> 
#include <sys/time.h> 
#include <sys/types.h> 
#include <sys/socket.h> 
#include <netinet/in.h> 
#include <arpa/inet.h> 
#include <signal.h> 
#include <pthread.h> 
#include <errno.h> 
#include <dirent.h>

void printf_data( char *src , unsigned int lens );

int main()
{
#ifdef TEST1
	char src[4] = "sjn";//test1
#endif

#ifdef TEST2
	char src[8] = "sjn";//test2
#endif

#ifdef TEST3
        char src[8] = {0};
	memset( src , 2 , 3 );//test3
#endif
        char dst[8] = {0};
        memset( dst , 1 , 8 );
	
	strncpy( dst , src , 8 );
	printf_data(dst , 8);
	memset( dst , 1 , 8 );
	
	snprintf( dst , 8 , "%s" , src );
	printf_data(dst , 8);
	memset( dst , 1 , 8 );
	
	strncpy( dst , src , 2 );
	printf_data(dst , 8);
	memset( dst , 1 , 8 );
	
	snprintf( dst , 2 , "%s" , src );
	printf_data(dst , 8);
	memset( dst , 1 , 8 );
				
	return 0;
}

void printf_data( char *src , unsigned int lens )
{
	int i = 0 ;
	for( i = 0 ; i < lens ; i++ )
		printf("%x," , src[i]);
	printf("\n");
}

实验了三种情况,对比strncpy和snprintf在三种不同情况下是否会出现异常的拷贝现象。三个test的打印结果如下

test1:

可以看出,

在src只有4的情况下,strncpy依然拷贝了8个字节的数据,如果src[4]-src[7]的数据非法,有可能造成错误。,当只拷贝两个字节时,strncpy也不能使dst成为一个字符串。

在src只有4的情况下,snprintf做到了只拷贝前3个字节的数据并添加\0,且当只拷贝两个字节时,也不会因为src中没有拷贝到\0而造成dst不是一个字符串。

test2:

结果和test1一致

test3:

这个实验主要为了验证src本身就没有\0的情况。

结果也和test1的分析结果一致

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值