ProgrammingVery hardProduct company OA
What is the behavior?
What is the behavior?
int a[3] = {1, 2, 3};
memcpy(a, a + 1, 2 * sizeof(int));
printf("%d %d %d", a[0], a[1], a[2]);- A. 2 3 3, well-defined
- B. Undefined behavior: memcpy's source and destination regions overlap, which memcpy does not support (memmove is required)
- C. 1 2 3, well-defined since nothing actually changes
- D. Compilation error
Correct answer: B. Undefined behavior: memcpy's source and destination regions overlap, which memcpy does not support (memmove is required)
memcpy requires the source and destination memory regions to not overlap; here copying a[1..2] into a[0..1] overlaps by one element, which is undefined behavior — memmove exists precisely to handle this safely by copying through a temporary buffer or copying in the correct direction.
More C Programming questions
- What is the behavior? c void f(int n) { char buf[n]; for (int i = 0; i <= n; i++) buf[i] = 'a'; } int main(void) { f(10); }
- What is printed? c // file1.c int x = 10; // file2.c (same program, separate translation unit) extern int x; void show(void) {…
- What is printed? c int x = 100; void f(void) { int x = 5; { int x = 1; printf("%d ", x); } printf("%d ", x); } int main(void) { f()…
- What is printed? c int x = 5; int f(void) { int x = x + 1; return x; } int main(void) { printf("%d", f()); }
- What is printed? c int f(void) { static int x; return x++; } int main(void) { printf("%d %d %d", f(), f(), f()); }
- What is printed? c static int helper(int n) { return n 2; } int main(void) { printf("%d", helper(5)); }