ProgrammingHardTCS NQT · Product company OA

Which line correctly allocates space for a copy of a string pointed to by const char *s?

  1. A. char *d = malloc(sizeof(s));
  2. B. char *d = malloc(strlen(s) + 1);
  3. C. char *d = malloc(strlen(s));
  4. D. char *d = malloc(strlen(s) * sizeof(char *));

Correct answer: B. char *d = malloc(strlen(s) + 1);

strlen does not count the terminating '\0', so one more byte is needed. sizeof(s) is the size of the pointer (e.g. 8), not of the string. Multiplying by sizeof(char *) allocates far too much and shows the size was misunderstood.

More C Programming questions

Exams that ask this topic