1

I need to read the whole content of a binary file and pass it to my method that receives as input a char array. I have a doubt about casting:

infile.open(argv[1], std::ios::binary);
infile.seekg(0, std::ios::end);
size_t file_size_in_byte = infile.tellg();
std::vector<char> data;
data.resize(file_size_in_byte);
infile.seekg(0, std::ios::beg);
infile.read(&data[0], file_size_in_byte);

How can I cast the vector to a char array now without having security memory errors?

0

1 Answer 1

1

&data[0] is actually your cast. As long as your vector doesn't go out of scope, you don't free that pointer don't go past file_size_in_byte / data.size(). you can safely read through it. like:

char* data_ptr = &data[0];

for(int i = 0; i < file_size_in_byte; i++)
{
   // do something with data_ptr[i]
}

or pass it to a function as in:

char* data_ptr = &data[0];

process_file_data(data_ptr, data.size());

Or, as grizzly mentioned on the comment below, simply use: char * data_ptr = data.data();

Sign up to request clarification or add additional context in comments.

2 Comments

Or char * data_ptr = data.data();
That is very true

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.