Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why is `unsigned char buf[length]` not compatible to `unsigned char**`?

C++ 12.2.0 throws the error

error: cannot convert ‘unsigned char (*)[91]’ to ‘unsigned char**’

on the following c++11 code snippet:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

unsigned char buffer[91];

// int i2d_PUBKEY(EVP_PKEY *a, unsigned char **pp);
ptrdiff_t length = i2d_PUBKEY(m_pkey, &buffer);
  • Defining unsigned char *buffer fixes the error, but leaves the array length unspecified.
  • I had assumed unsigned char buffer[91] decays into unsigned char *buffer.

Explicitely casting like i2d_PUBKEY(m_pkey, (unsigned char **)&buffer) makes the error go away, but the code segfaults then. I suppose there is something fundamental I don’t understand with respect to C++ arrays.

Can someone tell me how to write the code above so it works as intended?

>Solution :

The first thing to note is that neither of two pointers in the signature is const. This alone should warn you because the function could modify data at two different locations, but you’re passing only one (unless you expect buffer itself to change, which I guess you don’t). The documentation reads:

If pp is not NULL, it writes the encoded data to the buffer at *pp, and increments it to point after the data just written.

Let’s introduce the second variable to be modified:

unsigned char* ptr = &buffer[0];

Now we can pass this variable to i2d_PUBKEY():

i2d_PUBKEY(/* ... */, &ptr);

This call will write data into *ptr, i.e. into buffer. ptr itself will be modified, and that’s why ptr can’t be passed by value and a second pointer is needed – or a reference if i2d_PUBKEY() were a C++ function.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading