Answers/Solutions to Exercises in Chapter 3, Exercise 10

E10: Since we did not want to make an error in counting of bytes, we used the following code:
    char *p;
    ...
    p = malloc(strlen("hello")+1);
    strcpy(p,"hello");

instead of the intended
    char *p;
    ...
    p = malloc(6);
    strcpy(p,"hello");

Compare the memory requirement of both versions, which one requires less memory?

A10: Well, this is again one of those questions that cannot be really answered without knowing more about the circumstances, in this case the compiler. If it is a semi-decent compiler, both version will use exactly the same amount of memory. However, in the first version, there are two occurrences of a literal string "hello" and a bad compiler will store them separately, which will increase the memory requirements of the first version in comparison to the second version. A very good compiler could in fact compute strlen("hello")+1 during compilation, in which case the first version would be identical to the second version in memory requirements, yet safer and more proper.

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