Answers/Solutions to Exercises in Chapter 4, Exercise 5

E5: In a program we allocated 20 bytes of memory using p = malloc(20), yet we only need 10. For the efficiency reason we decided to "return" a portion of the segment to the memory manager using free(&p[10]). What will happen?
Will it compile? If so, will the program execute correctly and cause memory segment fragmentation? Or will it not work as intended --- the memory manager will not "accept" the memory and the program will continue executing? Or the program will be terminated?

A5:  We discussed one of the "rules" for memory allocation/deallocation: you can deallocate only segments you allocated. So, this is not correct. The compiler will not complain (it has no reason to), so it will compile fine. Will it run? Well, it depends on the operating system and how the standard function free() is implemented for the particular platform, the particular operating system, and the particular compiler. However, in majority of situation, it will at least compromise and confuse the memory manager, but most likely it will crash the program.

Back to Answers/Solutions Index                          Back to Answers/Solutions for Chapter 4 Index