I have a multiple choice question about memory allocation C, but I’m sure which one is the right answer.
-
Which of the following statments about releasing memory allocation is false?
a. It is an error to dereference a pointer to allocated memory after the memory has been released.
b. It is an error to
freememory with a pointer to other than the first element of an allocated array.c. Memory should be freed as soon as it is no longer needed.
d. Only one call to
freeis necessary to release an entire array allocated withcalloc.e. To ensure that it is released, allocated memory should be freed before the program ends.
They all look right to me 🙁 ! Any idea?
Thanks
As given by the other answers, e is the answer. The interesting option however is c which is highly subjective. There’s not necessarily any reason to free memory as soon as possible, and it’s favorable to delay this in certain circumstances.
For example, if you know that a certain memory block will be surely re-allocated soon after it’s freed, it may cost less to simply retain it in a pointer, rather than freeing it. It would hopefully be clear in each case whether having such a retained pointer makes sense and fits within the architecture of the code (code smell!). Sometimes a minor performance loss wins over having less readable code — use your judgment and measure if unsure!