And the exercise asks "What will be written at the file?". Could someone help out?
I know that sizeof(unsigned short) is 2 bytes while sizeof(unsigned char) is 1 byte so IF the program ran it would write 1 1 2?
Also, I have another issue: Is the first line of the code valid? Because I tried running it in VS and I had an error "Too many initializer values" on this line which makes sense because it doesn't seem like a right way to initialize an array. Could someone help me with both questions? Thanks a lot.
Note: At the end of the question, it is remarked at the paper that this specific code has some dangers (aka the teacher knows this is some bad code) and asks what kind of dangers do we see here.
It looks like line 4 is trying to point number_array at an array of 3 unsigned chars. Line 8 points s_p at the same array. Line 9 pre-increments s_p and then changes what it points to.
On many computers, unsigned short is 2 bytes. Now remember that when you increment a pointer, you increment it by the size of what it points to, line 9 increments the pointer by 2 bytes and then writes an unsigned short (2 bytes) at that location.
Kaboom! that means line 9 is probably writing to the 3rd byte of the array at line 4, AND to the byte that comes after that. This is undefined behavior and the program could do anything at all after this point.
Line 10 doesn't do what it appears to want either. number_array is a pointer, so sizeof(number_array) is the size of the pointer, not the size of the array. The pointer will probably be 4 or 8 bytes, depending on whether you're on a 32 or 64 bit machine.
Thanks so much for your prompt responses! These papers are full of "messed-up" code like this and it has made my brain hurt. Didn't consider the error at line 10...Great point made there.
Thanks again!