[Solved] Changing vector in function by pointer


The function does not make sense.

For starters it is unclear why you are using a pointer to the vector instead of a reference to the vector.

Nevertheles, this declaration

vector<unsigned char> vec(5);

does not reseeve a memory for the vector. It initializes the vector with 5 zero-characters which will be appended with other characters in the function.

The expression

&(*result).back()

returns reference to the last element of the vector. And this call

memcpy(&(*result).back(), elem, elem_size);

will try to overwrite memory that does not belong to the vector. As result the function has undefined behaviour.

Youy can imagine the situation the following way

   vector
|0|0|0|0|0|
        |a|b|c|d|
         string

so as it is seen there is an attempt to copy characters ‘b’, ‘c’, and ‘d’ to the memory that does not belong to the vector.

You should use methods of the class template std::vector to append new elements.

The function can look the following way as it is shown in the demonstrative program (provided that you want to use a pointer to vector).

#include <iostream>
#include <vector>
#include <string>

void addElem( std::vector<unsigned char> *result, const std::string &str_to_add ) 
{
    result->reserve( result->size() + str_to_add.size() );
    result->insert( result->end(), str_to_add.begin(), str_to_add.end() );
}   

int main() 
{
    std::vector<unsigned char> vec;
    std::vector<unsigned char> *vec_ptr = &vec;

    addElem( vec_ptr, "abcd" );

    for ( auto c : *vec_ptr ) std::cout << c;
    std::cout << std::endl;

    return 0;
}

Its output is

abcd

1

solved Changing vector in function by pointer