0

In this snippet of code, is there anything that could go wrong?

int min(int x, int y, int z) {
  if (x < y) {
    if (x < z)
      return x;
    else
      return z;
  } else if (y < z) {
    return y;
  } else
    return z;
}

int d(char* a, char* b, int n, int m) {
  if (n == 0)
    return m;
  if (m == 0)
    return n;
  if (a[n-1] == b[m-1])
    return d(a, b, n-1, m-1);
  return 1 + min(d(a, b, n, m-1), d(a, b, n-1, m),d(a, b, n-1, m-1));
}

int main() {
  printf("%d ", d("1111", "1100", 4, 4));
  printf("%d ", d("01", "1100", 2, 4));
  printf("%d", d("araba", "aba", 6, 3)); /// here
}

Note that on the last function call the size of the char array given to the function is one more than what it should be.

So essentially

a[5] is accessed, even though the size of a is 5.

What I know is since char pointer to string literal has /0 at the end; so although not sure, this is not out of bounds access.

This was a question that has been given on a test for choosing people for a computer olympiad camp and was cancelled for a reason not given. I was thinking if that was the right call, thanks in advance.

bedirhan
  • 21
  • 2
  • It is perfectly wholesome and legal to access the index of a null char in the array or string literal. Accessing this char won't introduce UB, but it might introduce a bug into your algorithm, which appears to be a recursive reverse string compare. – selbie Apr 29 '22 at 02:18
  • Code works as expected but the problem itself got cancelled as I said for a reason they didn't explicitly stated. But thanks, I appreciate it. – bedirhan Apr 29 '22 at 04:35

1 Answers1

1

"even though the size of a is 5" --> "araba" is size 6.

Try

printf("%zu\n", sizeof("araba")); 

Reading a string literal's null character is fine.

chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256