版权声明:欢迎转发,转发请标明出处 https://blog.csdn.net/weixin_39465823/article/details/88919347
代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *MyStrCopy1(const char *s1)
{
if(NULL == s1)
{
return "string is NULL";
}
else
{
char *s2 = (char *)malloc(strlen(s1)+1);
if(NULL == s2)
{
return "malloc error";
}
char *p = s2;
while((*s2++ = *s1++));
return p;
}
}
char *MyStrCopy2(const char *s1,char *s2)
{
char *p = s2;
while(*s2++ == *s1++);
//while(*s2++ = *s1++);
return p;
}
int main(int argv,char **argc)
{
const char *str1 = NULL;
const char *str2 = "string copying";
char str3[strlen(str2)+1];
//char str3[20];
printf("%s\n",MyStrCopy1(str1));
printf("%s\n",MyStrCopy1(str2));
char *res = MyStrCopy2(str2,str3);
printf("%s\n",res);
return 0;
}
编译调试:
gyz@debian:~/mc$ gcc strcopy.c -o strcopy -g -Wall
gyz@debian:~/mc$ ./strcopy
string is NULL
string copying
gyz@debian:~/mc$ gdb strcopy
结果发现另外一个字符串拷贝函数MyStrCopy2()没有用,调试一下看看。
设置断点的,展示代码的,这里不再啰嗦,直接上新内容。
(gdb) b 41
Breakpoint 1 at 0x8a9: file strcopy.c, line 41.
(gdb) r
Starting program: /home/gyz/mc/strcopy
string is NULL
string copying
Breakpoint 1, main (argv=1, argc=0x7fffffffe228) at strcopy.c:41
41 char *res = MyStrCopy2(str2,str3);
(gdb) s
MyStrCopy2 (s1=0x555555554990 "string copying", s2=0x7fffffffe0c0 "\001")
at strcopy.c:27
27 char *p = s2;
(gdb) n
28 while(*s2++ == *s1++);
(gdb) p s2
$1 = 0x7fffffffe0c0 "\001"
(gdb) n
30 return p;
(gdb) p s2
$2 = 0x7fffffffe0c1 ""
(gdb)
结果发现问题所在了,p s2了两下,发现s2的值只增加了1,那就奇怪了,仔细观察才发现while里面用了两个=。
解释:
1,s就是step,可以进入函数;
2,p就是print,打印变量。