Solutions to End of Chapter Problems

advertisement

Solutions to End of Chapter Problems

Problem 1. (a) alpha_ptr = (char*) malloc(20);

(b) free ( alpha_ptr );

(c) When you no longer need the memory on the heap, it is good to free it up so that it can be reused. Poor management of the heap (not freeing it up) could cause you to run out of memory on the heap.

Problem 2. The "Boolean expression" is not really a Boolean expression; it is an assignment statement.

Assignment statements always evaluate to true . Thus, this program has an infinite loop that continually adds to the heap every time it iterates, without ever freeing up any space on the heap.

Eventually, we exhaust all the space on the heap and the OS kills the program.

Problem 3. When declaring an array (i.e., a buffer), only a finite amount of bytes of memory are reserved. If the array is filled with more bytes of data than it has reserved, the data will overflow into following bytes of memory. This overflow of data beyond the bounds of the array is a buffer overflow. This problem arises from a fundamental issue with the C programming language: the compiler does not prevent a program from running beyond the bounds of an array.

Problem 4. (a) 12

(b) nickname is a string so a NULL character will automatically be appended to the end.

Since highscore is an integer, you would have to enter 15 bytes. Those 15 bytes plus the NULL character will fully write over highscore . (Note that only entering in 12 plus the NULL character will change the value of highscore .)

(c) Declare highscore last, as in: char user[16]; char nickname[x]; int highscore;

(d) If we enter 32 bytes (12 for nickname , 4 for highscore and 16 for user ) then the

NULL which is automatically appended will begin to overwrite the Saved ebp . Once the Saved ebp has begun to be overwritten, a segmentation fault will occur and the program will crash.

(e) 16963 converted to hex is 4243. 42 in ASCII is the letter ‘B’ and 43 in ASCII is the letter ‘C’.

Since is an integer requires 4 bytes and are stored in memory in little endian, we need to overwrite highscore with 43 42 00 00.

We will make the assumption that highscore was initialized to 0. This will make the right byte already 00.

Then when we enter the string IDoABCsLikeACB , the C and B overflow into highscore and a NULL character is appended to the end of the string leaving highscore to have a value of 16963.

Problem 5. (a)

5

Download