关于一个栈的异常

   今天在写一段小代码时,无意中忽视了一个问题,忽视了字符串的长度而导致的栈异常,当看到此贴的朋友看到下面这段代码时候,不妨亲自编译运行下

#include <map>
#include <string>
#include <iostream>
using namespace std;

#define SUCCESS                  0x0
#define ALLOCATE_MEMORY_FAILED   0x2
#define INVALIDATE_POINTER       0x3

int RemoveRepeatedChar(char *str)
{

 int i=0;
 int j=0;
    int lenth=0;

    if( NULL == str )
 {
        return INVALIDATE_POINTER;
 }
   
    lenth = strlen(str);

 // insert a '%' at the head and the last
 for ( i=lenth; i>=0; --i )
 {
        str[i] = str[i-1];
 }
   
 str[0] = '%';
 str[lenth + 1] = '%';
 str[lenth + 2] = '/0';
   
 lenth = strlen(str);
    i = 0;
 j = 0;
   
 // remove repeated '%' in str
    for (j=i+1;j<lenth;j++)
    {
        if(str[i]!=str[j])
            str[++i]=str[j];
    }

    str[i+1]=0;

    return SUCCESS;
}

int main()
{
   char StrDouble[] = "%%%abcd%%%%%adf%ff%%ffd%%%%%";
   char StrSimple[] = "abde";
   char StrThird[] = "%abcdfdjf%";

   RemoveRepeatedChar(StrDouble);
   RemoveRepeatedChar(StrSimple);
   RemoveRepeatedChar(StrThird);

   cout<<StrDouble<<endl;
   cout<<StrSimple<<endl;
   cout<<StrThird<<endl;

   return 0;
}

 

大家看到这个输出结果后

%abcd%adf%f%fd%

 

%abcdfdjf%

 

会对第二行的输出有些疑问,为什么会变成一个NULL呢,我跟踪过,也看过反汇编出来的代码,不过有个问题,当我去反汇编跟踪时候,能输出正确的结果,这点令我很疑惑,而且也不会出现栈异常。当然了,这个问题我说到了这个点子上,我想看到这个帖子的朋友,也应该能明白到底是什么原因所导致的。

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值