Be carefull when using string operating function declarated in "string.h"

        as we know that by adding "#include<string.h>"  in the head of the code, we benifit a lot from the string operating funtion , such as strcpy() ,strncpy, strcmp() , strncpy ...., and so on.

       however it's also easy to make your process crash if you give a NULL value point param to those string operating funtion, such as :


/* strncmp.c by vinco at 2011-08-03
*  ubuntu 9.10 CC/GCC
*/
#include<string.h>
#include<stdio.h>
#include<stdlib.h>
#define BUFLEN_32 32

int strncasecmp_s(const char *s1,const char *s2,int n);
char* strncpy_s(char *dst, char * src ,int n);

int main()
{
	//char s1[BUFLEN_32]="zhang";
	//char s2[BUFLEN_32];
	//bzero( s2, BUFLEN_32 );// bzero(s2,sizeof(s2))

	char* s1 ="zhang";
	//char* s2 = (char*)malloc(BUFLEN_32);
	char* s2 = NULL;

	//printf("s1 = %s\ns2 = %s\n",s1,s2);
	//printf("s1 = %p\ns2 = %p\n",s1,s2);

#if 1
	if(!(strncasecmp(s1,s2,BUFLEN_32)))
#else
	if(!(strncasecmp_s(s1,s2,BUFLEN_32)))
#endif
	{
		printf("they are equal\n");
	}
	else
	{
		printf("not equal\n");
	}

#if 1
	strncpy(s2,s1,BUFLEN_32);
#else
	strncpy_s(s2,s1,BUFLEN_32);
#endif
	printf("s1 = %s\ns2 = %s\n",s1,s2);
}

int strncasecmp_s(const char *s1,const char *s2,int n)
{
	char emptystr='\0';
	const char *str1=s1;
	const char *str2=s2;

	if(str1==NULL) str1=&emptystr;
	if(str2==NULL) str2=&emptystr;

	return strncasecmp(str1,str2,n);
}

char* strncpy_s(char *dst, char * src ,int n)
{
	if(dst == NULL || src ==NULL)
		return NULL;
	return strncpy(dst,src,n);
}

1. in this case we take the following function specifically :

char * s2 = NULL
if(!(strncasecmp(s1,s2,BUFLEN_32)))

 
 

 
strncpy(s2,s1,BUFLEN_32);

 

  compile and run specifically 

root@vinco:/home/vinco# gcc strncasecmp.c  -o strncasecmp
root@vinco:/home/vinco# ./strncasecmp 
Segmentation fault
root@vinco:/home/vinco# gcc strncasecmp.c  -o strncasecmp
root@vinco:/home/vinco# ./strncasecmp 
not equal
Segmentation fault

both strncmp() and strncpy() are not safety to our process if we just give it a NULL value point

 

2 . to void the unexpected crash , we should check the point before entry those function ,just as strncmp_s() strncpy_s() did,( _s means safety way)

or give enough memory as the comment say:

    i . use  array(it allocate memory abviously):

	char s1[BUFLEN_32]="zhang";
	char s2[BUFLEN_32];
   

    ii . allocate memory for the point by yourself(remember to add free() if your want to porting it to a big project )

char* s2 = (char*)malloc(BUFLEN_32);



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值