ProgrammingModerateTCS NQT · Product company OA

What is wrong with this code?

What is wrong with this code?
char *s = malloc(5);
strcpy(s, "hello");
  1. A. strcpy cannot copy into memory from malloc
  2. B. It leaks memory because strcpy allocates a second copy
  3. C. "hello" needs 6 bytes including '\0', so strcpy writes past the 5-byte block: undefined behaviour
  4. D. Nothing: malloc always rounds sizes up, so it is safe

Correct answer: C. "hello" needs 6 bytes including '\0', so strcpy writes past the 5-byte block: undefined behaviour

strcpy copies the terminator too, writing 6 bytes into a 5-byte block. It may appear to work because allocators often round up, but the behaviour is undefined. Allocate strlen(src) + 1.

More C Programming questions

Exams that ask this topic