I need to copy modified data that is stored in an char* to another char* but I get an access violation error.

Here is the code

        int EncryptData(char *data_source, char *data_cipher, size_t sizeofdata)
        {
            char *tmp_data;
            long long int digit;
            tmp_data = new char[sizeofdata];

            /*
                Do some calculations here with some data and then store it in tmp_data.
            */

            memcpy(data_cipher, tmp_data, sizeof(data_cipher));
            delete[] tmp_data;
        }

// char* dest
int main()
{
    char *dest = "";
    encryption.EncryptData("Hello world", dest, strlen("Hello world"));

        for(int i = 0; i < strlen(dest); i++)
        std::cout << dest[i];
}

When I copy tmp_data to data_cipher, dest should then hold the modiefied values. But I get an acces violation when I try to copy the data.

How do I fix it?

Recommended Answers

All 2 Replies

line 11. sizeof a pointer always returns 4 on 32-bit compilers. There is no way for the compiler to determine the length of the data to which the pointer addresses.

Also about that same line and line 18. line 18 creates a pointer to a 1-byte string, yet on line 11 you are attempting to copy more than 1 byte to that memory. This is guaranteed to crash the program.

How do I fix it?

        int EncryptData(char *data_source, char *data_cipher, size_t sizeofdata)
        {
            char *tmp_data;
            long long int digit;
            tmp_data = new char[sizeofdata];

            /*
                Do some calculations here with some data and then store it in tmp_data.
            */

            memcpy(data_cipher, tmp_data, sizeofdata);
            delete[] tmp_data;
        }

// char* dest
int main()
{
    char dest[255] = {0};
    encryption.EncryptData("Hello world", dest, strlen("Hello world")+1);

        for(int i = 0; i < strlen(dest); i++)
        std::cout << dest[i];
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.