On Wed, Apr 26, 2023 at 11:16 PM Jeffrey Walton <noloa...@gmail.com> wrote:
>
> On Wed, Apr 26, 2023 at 6:13 PM Dwight Kulkarni <dwi...@realtime-7.com> wrote:
> >
> > I ran address sanitizer:  Heap use after free is the problem.  I had to use 
> > the NEW operator to allocate the ram.  What is weird is that usually it 
> > will error out right away after it goes out of scope, but this was delayed 
> > in recovering the memory, so it was working and then poof the memory 
> > disappears, but there is no access violation, it just returns bad result 
> > but only sometimes. Other times it is working and if there is a delay then 
> > the RAM gets reclaimed in that time and the error occurs right in the 
> > middle of the function. Really freaky.
> >
> > char* convert_cryptopp_integer_str(Integer n, size_t& msg_len){
> > const size_t len = n.MinEncodedSize(Integer::UNSIGNED);
> > char* v = new char[len];
> > msg_len = len;
> > n.Encode((byte*)v, len, Integer::UNSIGNED);
> > return v;
> > }
> >
> > std::vector<byte>* convert_cryptopp_integer(Integer n){
> > const size_t len = n.MinEncodedSize(Integer::UNSIGNED);
> > std::vector<byte>* v = new std::vector<byte>(len);
> > n.Encode((byte*)v, v->size(), Integer::UNSIGNED);
> > return v;
> > }
>
> So C-ish... Stop managing allocations with new and free. Let the std
> C++ library do the work for you:
>
> std::string convert_cryptopp_integer_str(const CryptoPP::Integer& n)
> {
>     using namespace CryptoPP;
>
>     const size_t len = n.MinEncodedSize(Integer::UNSIGNED);
>     std::string v;
>     v.resize(len);
>
>     n.Encode((byte*)&v[0], v.size(), Integer::UNSIGNED);
>     return v;
>
> }
>
> std::vector<CryptoPP::byte> convert_cryptopp_integer(const CryptoPP::Integer& 
> n)
> {
>     using namespace CryptoPP;
>
>     const size_t len = n.MinEncodedSize(Integer::UNSIGNED);
>     std::vector<byte> v(len);
>
>     n.Encode((byte*)&v[len], v.size(), Integer::UNSIGNED);
>     return v;
> }

I probably should have said... This is the _portable_ way to get the
non-const pointer to the first element in the array:

    n.Encode((byte*)&v[0], v.size(), Integer::UNSIGNED);

It is portable because it works with C++98 and above. Other methods
exist, but they work with C++11 and above.

This was wrong. It should have used element 0, not element 'len':

    n.Encode((byte*)&v[len], v.size(), Integer::UNSIGNED);

Jeff

-- 
You received this message because you are subscribed to the Google Groups 
"Crypto++ Users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to cryptopp-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/cryptopp-users/CAH8yC8nzj4itGXwqvbXEVw9w396qJtfyYWb_1--aRny7h6Z3aQ%40mail.gmail.com.

Reply via email to