krb5: crypto.c avoid realloc to trim memory allocation
commit1b1ff8fdd571f66624cf744b2333493cc7e781d4
authorJeffrey Altman <jaltman@auristor.com>
Wed, 19 Apr 2023 12:33:25 +0000 (19 08:33 -0400)
committerJeffrey Altman <jaltman@auristor.com>
Wed, 3 May 2023 21:02:34 +0000 (3 17:02 -0400)
tree13e85a5a1be8ae46eb25914a106a7663179aad38
parentd280a83ebe3449974fedcdaf88238fde0edc0b10
krb5: crypto.c avoid realloc to trim memory allocation

decrypt_internal_derived(), decrypt_internal_enc_then_cksum(),
decrypt_internal(), and decrypt_internal_special() execute the
following pattern where 'p' is an allocation of size 'len'

  l = len - n
  memmove(p, p + n, l);
  result->data = realloc(p, l);
  if (result->data == NULL && l != 0) {
      free(p);
      return krb5_enomem(context);
  }
  result->length = l;

which when compiled by gcc 13.0.1-0.12.fc38 or gcc-13.0.1-0.13.fc39
generates the following warning

  warning: pointer 'p' may be used after 'realloc' [-Wuse-after-free]

The C language specification indicates that it is only safe to free()
the pointer passed to realloc() if errno is set to ENOMEM.  Yet the
warning is generated by the following pattern

  l = len - n
  memmove(p, p + n, l);
  errno = 0;
  result->data = realloc(p, l);
  if (result->data == NULL && l != 0) {
      if (errno == ENOMEM)
          free(p);
      return krb5_enomem(context);
  }
  result->length = l;

The value of performing the realloc() is questionable.  realloc()
in many cases will need to perform a second allocation of the
smaller size and then perform a memcpy() which will slow down
the operation without saving much memory.  The allocation is already
very small.

This change avoids the warning by removing the realloc() entirely.
lib/krb5/crypto.c