关于strcpy的实现.
1 #include <stdio.h> 2 #include <stdlib.h> 3 4 5 int strlen(const char *str) 6 { 7 int length=0; 8 while(*str++!='\0') 9 { 10 length++; 11 } 12 return length; 13 } 14 15 char *strcopy(char *dest,const char *source) 16 { 17 if(source==NULL) 18 { 19 printf("Error:StrSource is NULL \n"); 20 } 21 dest=(char *)malloc(strlen(source)+1);//多一个空间用来存储字符串结束符'\0' 22 23 char *p=dest; 24 while(source!='\0')//这里应该改为while(*source!='\0').... 25 { 26 *p++=*source++; 27 } 28 *p='\0'; 29 return dest; 30 } 31 32 int main() 33 { 34 const char *src="fuckoff jerk!!"; 35 char *des=NULL; 36 des=strcopy(des,src); 37 if(des!=NULL){ 38 free(des); 39 des=NULL; 40 } 41 return 0; 42 }
以上代码.编译通过. 运行时出现段错误.
请大家帮我看看问题出在哪里..