T Eom
T Eom

Reputation: 95

Why vector cause Segmentation fault Error?

I wanted to make Random number from Openssl.

So. I made program :

#include "openssl/rand.h"
struct randomData
{
     char str[32];
}

int main()
{
    std::vector<randomData> vecStr;
    randomData rd;
    vecStr.emplace_back(rd);

    RAND_bytes((unsigned char *)vecStr[i].str, sizeof(vecStr[i].str));

    std::string ss = to_hex(vecStr[i].str, sizeof(vecStr[i].str));
    std::cout << "Random Nonce Hex Data : " << ss << " // Key Length : " << ss.length()<<std::endl;

    return 0;
}
// [out put]
// Random Nonce Hex Data : f0f5e38e596fdb2f7cef79d3706fcbf111decaa844154295b89b90eb65925a53 // Key Length : 64

But I don't want to make struct. Just use vector. So, I tried.

std::vector<char> str;
str.reserve(33);
RAND_bytes((unsigned char *)&str, sizeof(str));
std::string ss = to_hex((char*)&str, sizeof(str));
std::cout << "Random Nonce Hex Data : " << ss << " // Key Length : " << ss.length() << std::endl;

// [ output ]
// Random Nonce Hex Data : f1935de540b5a75bcaa9eab4b173abcb6a840bf83c4181ee // Key Length : 48
// Segmentation fault (core dumped)

You can see the error log. I searched a difference "reserve" with "resize". But those function caused same error.

Why this happen??

Upvotes: 1

Views: 280

Answers (1)

L. F.
L. F.

Reputation: 20579

First, it should be resize, not reserve.

Second, use .data() instead of a cast to pointer type.

Third, it is str.size(), not sizeof(str).

std::vector<char> str(33);
RAND_bytes(reinterpret_cast<unsigned char*>(str.data()), str.size());
std::string ss = to_hex(str.data(), str.size());

Upvotes: 5

Related Questions