ProgrammingModerateTCS NQT · Product company OA
What is wrong with this code?
What is wrong with this code?
char *s = malloc(5); strcpy(s, "hello");
- A. strcpy cannot copy into memory from malloc
- B. It leaks memory because strcpy allocates a second copy
- C. "hello" needs 6 bytes including '\0', so strcpy writes past the 5-byte block: undefined behaviour
- 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
- With 4-byte int, what is printed? c int a[3] = {7, 8, 9}; int (p)[3] = &a; printf("%d %d %zu", (p)[1], p + 1, sizeof p);
- What is printed? c int c = 0, calls = 0; void comb(int start, int n, int k) { calls++; if (k == 0) { c++; return; } for (int i = start; i…
- What is printed? c int x = 3, y = 1; printf("%d %d", !x == y, !(x == y));
- For ints a and b with b != 0 and no overflow, which statement is always true in C99 and later?
- Why should a header file shared by several .c files not contain the line int counter = 0;?
- With 4-byte int, what is printed? c int n = 0; int f(void) { n++; return 1; } int main(void) { sizet s = sizeof(f()); printf("%zu %d", s…