gdb调试字符串倒序

/*hello.c(字符串倒序)*/

#include <stdlib.h>

#include <string.h>


static void my_print (char *);
static void my_print2 (char *);


main ()
{
char my_string[] = "hello world!";
my_print (my_string);
my_print2 (my_string);
}
void my_print (char *string)
{
printf ("The string is %s ", string);
}
void my_print2 (char *string)
{
char *string2;
int size, i;
size =strlen (string);
string2 = (char *) malloc (size + 1);
for (i = 0; i < size; i++)
string2[size -- i] = string[i];
string2[size+1] = '\0';  //26

printf ("The string printed backward is %s ", string2);

}

在命令行输入$ gcc -g -o hello hello.c

$./hello

执行后显示如下结果:

The string is hello wrold!

The string printed backward is  

第二行打印的并不是我们所期望的,我们所预想的应该是:The string printed backward is !dlrow olleh

肯定是因为某种原因void my_print2(char*string)没有工作

用gdb调试如下

输入:gdb hello

(gdb) run
Starting program/root/hello
The string is hello world!
The string printed backward is
Program exited with code 040


list 

list

list

gdb) break 26
gdb 将作出如下的响应:
Breakpoint 1 at 0x804857cfile hello.c, line 26. //在第26行设置断点
(gdb)

(gdb) watch string2[size - i]
gdb 将作出如下回应:
Hardware watchpoint 2string2[size - i]
经过一次循环后:
Hardware watchpoint 2string2[size - i]
Old value = 0 '00'
New value = 104 'h'
my_print2 (string=0xbffffab0 "hello world!") at hello.c25
25 for (i = 0; i < size; i++)


分析:size =12,当i=11时,表达式string2[size--i]表示第1个字符‘!’最后一个字符已经拷贝到新字符串了,再把循环执行下去已经没有值在分配给字符串string2[0],因而打印print2时没有任何输出,修正这个错误很容易,只需要把第一个字符的偏移量改为size-1 而不是size 

string2[size-1-i]=string[i];

string2[size]='\0';


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值