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);
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
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);