Run time Failure- Stack around the variable was corrupted

I hit upon this run time failure.
Looks like some initialization error
The purpose of this program is to reverse a string word by word.
Input String : "This is a Test String"
Output String: "String Test a is This"

<<<<<<<<<<<<<<<<<<<<<<<<<<<Begin of code>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
#include "stdafx.h"
#include "conio.h"
#include "iostream"
#include "string.h"
using namespace std;

char* reverse(char *s,int start,int last)
{
char temp;
if(start<=last)
{
temp = s[start];
s[start]=s[last];
s[last]=temp;
reverse(s,start+1,last-1);
}
return s;
}

char* reverse_word(char *s,int start,int last)
{
s = reverse(s, start,last);
int temp,word_last,word_start;
word_start=temp= start;
while(s[temp]!='\0')
{
while(s[temp]!=' ')
{
temp++;
if(s[temp]=='\0')
break;
}
word_last = temp-1;
s= reverse(s,word_start,word_last);
temp++;
word_start=temp;
}
return s;
}

void ReverseAndTest(char str1[],char str2[])
{
int print_flag=1;
if(strlen(str1)!=strlen(str2))
cout<<"The input test case string lengths do not match"<<endl;
str1 = reverse_word(str1,0,(strlen(str1)-1));
for(int i=0;i<strlen(str1);i++)
{
if(str1[i]!=str2[i])
{
cout<<"Test Failed"<<endl;
print_flag=0;
break;
}
}
if(print_flag)
cout<<"Test Passed"<<endl;
}

int main(void)
{
//test 1
char test1[] = "My name is ABCD";
char expected1[]= "ABCD is name ny";
ReverseAndTest(test1,expected1);

//test 2
char test2[] = "This is a test";
char expected2[]= "test a is This";
ReverseAndTest(test2,expected2);

//test3
char test3[] = " ";
char expected3[]= " ";
ReverseAndTest(test3,expected3);

getch();
return 0;
}

<<<<<<<<<<<<<<<<<<<<<<<<End of Code>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
It looks like this function is looping too many times - Can you recheck it

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
char* reverse_word(char *s,int start,int last)
{
    s = reverse(s, start,last);
    int temp,word_last,word_start;
    word_start=temp= start;
    while(s[temp]!='\0')
    {
        while(s[temp]!=' ')
        {
            temp++;
            if(s[temp]=='\0')
                break;
        }
        word_last = temp-1;
        s= reverse(s,word_start,word_last);
        temp++;
        word_start=temp;
    }
    return s;
}
That was the problem.
The test {s[temp]!='\0'} was wrong.
Changed the test condition and it worked.
Thanks guestgulkan!!!
Topic archived. No new replies allowed.