I just realized that PEM_write_bio_PUBKEY() doesn't actually zero-terminates its output so disregard the above. If you want to return it as a string, you have to allocate ptr->length + 1 bytes and zero-terminate it yourself.

If you strip out the newline, you can use the BIO_set_close() trick but you still need to zero-terminate it, presumably by doing `ptr->data[ptr->length - 1] = '\0'`. Check that the return value of PEM_write_bio_PUBKEY() > 0.