ProgrammingHardTCS NQT · Product company OA
Which line correctly allocates space for a copy of a string pointed to by const char *s?
- A. char *d = malloc(sizeof(s));
- B. char *d = malloc(strlen(s) + 1);
- C. char *d = malloc(strlen(s));
- 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
- What is printed? c int a = 3, b = 0; int r = (a > b) + (a && b) 2 + (a || b) 4 + !b 8; printf("%d", r);
- What is printed? c int a[] = {5, 1, 4, 2, 3}; int lo = a, hi = a + 4; while (lo < hi) { if (lo > hi) lo++; else hi--; } printf("%td %d"…
- What is printed? c long memo[50]; int calls = 0; long f(int n) { calls++; if (n < 2) return n; if (memo[n]) return memo[n]; return memo[n]…
- With 4-byte int, what is printed? c int x = 7; printf("%zu %zu", sizeof (int) 3, sizeof x + 1);
- What is printed? c char s[8] = {'a', 'b'}; printf("%zu %zu %d", strlen(s), sizeof s, s[7]);
- What does r(3) print, and how many digits would r(6) print? c void r(int n) { if (n == 0) return; r(n - 1); printf("%d", n); r(n - 1); }