explain the working of the code snippet

Hello

Please explain the working of the following code. I think I am getting
something wrong somewhere.

#include <stdio.h>
#include <string.h>
char a = ‘a’;
int main(int argc, char **argv){
printf("%s", &a);
strcpy (&a, “HELLOOOOOOOOOOOOOOOOOOOOOOOOOOOOO”);
printf("%s", &a);
return 0;

}

Thank you.

It’s going to fail at the strcpy because &a doesn’t point to sufficient storage to hold the long string, you’re going to clobber the stack.

ken yap wrote:

>
> It’s going to fail at the strcpy because &a doesn’t point to sufficient
> storage to hold the long string, you’re going to clobber the stack.
>
>
The point is it works.

If it does it’s by accident, maybe you are overwriting an area which you never return to anyway, since you exit() the program. I think that if you try that strcpy() in a function you may get a different result.

The point is that you cannot rely on it working correctly because you have a program error. The behaviour is indeterminate.

Hi,

I agree with ken_yap and only want to cite the man page (bugs section) from strcpy to point out that this is not the right usage of strcpy:

If the destination string of a strcpy() is not large enough (that is, if the programmer was stupid or lazy, and failed to check the size before copying) then anything might happen. Overflowing fixed length strings is a favorite cracker technique.

ken yap wrote:

>
> If it does it’s by accident, maybe you are overwriting an area which you
> never return to anyway, since you exit() the program. I think that if
> you try that strcpy() in a function you may get a different result.
>
> The point is that you cannot rely on it working correctly because you
> have a program error. The behaviour is indeterminate.
>

Well Ken I know that it works by accident and it is the accident that I want
to understand. Guide me.

I already proposed a likely explanation. You don’t use the area of the stack that you have destroyed because you are calling exit(). If you were to put that strcpy in a function, it would probably crash on the return from the function. Also the area of the stack above the stack pointer is finite. If you use longer strings, eventually at some point you will try to overwrite an area which is outside of your program’s area and cause an exception which will make the OS terminate your program on the spot.

If you wish to understand such pathologies you have to study how C code is turned into machine code and what the layout of machine memory looks like and how the machine’s registers are used. Otherwise if you just want reliable programs, avoid such errors.

sure, jumping from a bridge works too :stuck_out_tongue:

I wish you enjoyed the “undefined behaviour” show lol!