unexpected output

Discussion in 'C++' started by kaushalneo, Jul 16, 2009.

  1. kaushalneo

    kaushalneo New Member

    Joined:
    Jul 16, 2009
    Messages:
    1
    Likes Received:
    0
    Trophy Points:
    0
    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 a moderator: Jul 17, 2009
  2. xpi0t0s

    xpi0t0s Mentor

    Joined:
    Aug 6, 2004
    Messages:
    3,009
    Likes Received:
    203
    Trophy Points:
    63
    Occupation:
    Senior Support Engineer
    Location:
    England
    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.
     

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice