0
votes

I wrote the following piece of code and got the error mentioned above

Can someone tell me where i am going wrong

Thanks.

#include "iostream"
#include "sstream"
#include <string.h>

int main()
{
     std::string temp1 = "454552354772";
    char arr[16];
    memcpy(arr , &temp1 , temp1.size());
    std::string temp2;
    memcpy(&temp2 , arr , temp1.size());
    std::cout<<temp2;

}

the error i got was

*** Error in `./a.out': double free or corruption (fasttop): 0x00000000016c5010 ***
======= Backtrace: =========
/lib/x86_64-linux-gnu/libc.so.6(+0x80a46)[0x7fa91d359a46]
/usr/lib/x86_64-linux-gnu/libstdc++.so.6(_ZNSsD1Ev+0x20)[0x7fa91dc78290]
./a.out[0x400bc9]
/lib/x86_64-linux-gnu/libc.so.6(__libc_start_main+0xf5)[0x7fa91d2faea5]
./a.out[0x400a09]
3
Copying to the address of a std::string isn't possible. Not without invoking all kinds of undefined behavior.jogojapan
i am only copying the data from the address pointed by the std::string rite??user2454413
I meant the second memcpy statement. You copy from an array straight into a std::string object. Don't do that.jogojapan
How else can i copy the value of the array into the std::string??user2454413
Using the methods suggested by ForEveR's answer.jogojapan

3 Answers

1
votes

You cannot work with objects of string class this way.

memcpy(arr , &temp1 , temp1.size());

should be

temp1.copy(arr, temp1.size());

And

memcpy(&temp2 , arr , temp1.size());

should be

std::string temp2(arr, temp1.size());
0
votes

std::string is a dynamically allocated container. You should rarely use it as a destination for memcpy. In your code, there is no memory allocated for temp2. The workaround is to use string::reserve to preallocate memory.

However, there is usually no need to mix C-code (memcpy, char[]) with C++-code (std::string, std::cout). Apparently, you're doing something wrong.

0
votes

If you copy from the location of the string(it also contains functions, other data etc.), and copy 16 bytes, you end up with alot of unusable data.

You want the first character in the string, so you would do this: memcpy(arr, &temp1[0], temp1.size());

This would effectively copy it. When you want to do the opposite(copy to the string), why not just do this? std::string temp2(arr, temp1.size()); or std::string temp2((const char*) arr);