Go4Expert

Go4Expert (http://www.go4expert.com/)
-   C++ (http://www.go4expert.com/forums/cpp/)
-   -   unexpected output (http://www.go4expert.com/forums/unexpected-output-t18570/)

kaushalneo 17Jul2009 00:30

unexpected output
 
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

xpi0t0s 17Jul2009 01:50

Re: unexpected output
 
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.


All times are GMT +5.5. The time now is 21:59.