Would accessing a "\0" at the end of a char array result in undefined behavior in C?

56 Views Asked by At

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.

1

There are 1 best solutions below

0
On BEST ANSWER

"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.