ProgrammingThis forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.
Welcome to LinuxQuestions.org, a friendly and active Linux Community.
You are currently viewing LQ as a guest. By joining our community you will have the ability to post topics, receive our newsletter, use the advanced search, subscribe to threads and access many other special features. Registration is quick, simple and absolutely free. Join our community today!
Note that registered members see fewer ads, and ContentLink is completely disabled once you log in.
4 bytes I tried and was working fine, but if I give 10 bytes then, why i is being disturbed..?
because i points to k, and (and I think this is unspecified, though) probably k is stored in memory right after j. So, when you memcpy 10 bytes to j, the first 4 bytes (assuming your int is 4 bytes, which it most likely is) will be written to j, the next 4 bytes will rewrite k (which is where i points to, and the last two bytes will try to overwrite whatever happens to be there in the memory, perhaps some instructions or something like that. Of course the system does not like that.
A guide such as "Smashing the stack for fun and profit" explains what happens when you overflow the bounds of your automatic variables and damage other data on the stack. When programming in C you should take great care not to do this. In fact that's one of the major drawbacks of C.
but if I give 10 bytes then, why i is being disturbed..?
int *i,j,k = 10;
Assuming optimization is off, i, j and k are stored on the stack, almost certainly together and in a sequence that is up to the whim of the compiler and is not predictable.
You overwrite the 4 bytes of j and you overwrite whatever six bytes follow j. So if i happens to be directly after j, you overwrite all four bytes of i (and two more beyond). If k is after j and i after k, then you overwrite all four bytes of k and two bytes of i.
If you overwrite i with something that doesn't happen to be a valid address, then the next use of *i will seg fault.