Multiple choice

/* Read an arbitrarily long string. / int read_long_string (const char * const buf) { char * p = NULL; const char * fwd = NULL; size_t len = 0; assert(buf); do { p = realloc(p, len += 256); if (!p) return 0; if (!fwd) fwd = p; else fwd = strchr(p, ' '); } while (fgets(fwd, 256, stdin)); *buf = p; return 1; }

The function read_long_string(), defined above, contains an error that may be particularly visible under heavy stress. Which one of the following describes it?

  1. The write to *buf is blocked by the const qualifications applied to its type.

  2. If the null pointer for char is not zero-valued on the host machine, the implicit comparisons to zero (0) may introduce undesired behavior. Moreover, even if successful, it introduces machine-dependent behavior and harms portability.

  3. The symbol stdin may not be defined on some ANCI C compliant systems.

  4. The else causes fwd to contain an errant address.

  5. If the call to realloc() fails during any iteration but the first, all memory previously allocated by the loop is leaked.

Reveal answer Fill a bubble to check yourself
A Correct answer
Explanation

The function parameter is declared as const char ** const buf. The outer const means the pointer buf itself cannot be modified. The inner const means the char* pointers that buf points to cannot be modified. However, *buf = p attempts to modify buf[0] (the first char* pointer), which violates the inner const qualification. This would be caught by the compiler. Option B is incorrect - NULL comparisons are fine. Option C is wrong - stdin is always defined in ANSI C. Option D is incorrect - the else logic is valid. Option E describes a real leak but isn't the primary error a compiler would catch.