unexpected output

kaushalneo's Avatar, Join Date: Jul 2009
Newbie Member
please xplain the output of following program....

Code:
#include<iostream.h>
#include<conio.h>
#include<string.h>

void main(){
	char a[10];
	char b[10];
	char c[10];
	cin>>c;
	cin>>b;
	strcpy(a,c);
	cout<<a<<endl;
	strcat(b,c);
	cout<<b<<endl;
	cout<<a<<endl;
	int x=strcmp(a,c);
	cout<<x;
}
please xplain the output of the above program...

kaushal
swapnil
kaushal
swapnilkaushal
shal
8

Last edited by shabbir; 17Jul2009 at 09:34.. Reason: Code blocks
0
xpi0t0s's Avatar, Join Date: Aug 2004
Mentor
You have undefined behaviour, because b is not long enough for "swapnil"+"kaushal" - total 15 characters, but b is only 10 chars long.

So anything could happen, and the solution to the problem is to extend b to at least 15 characters so that it can cope with what you want to do. Or use strings so you can do b+=c without worrying about buffer sizes.

This is a buffer overflow bug.