I have written the following code which seems to be working fine with old std::string implentation. But with gcc 5.1, it crashes.
#include <string>
#include <iostream>
#include <cstring>
struct abc
{
public:
abc() {}
abc(const std::string& x)
: gullu(x)
{
}
std::string gullu;
};
int main()
{
abc *a = new abc("dhfghdf");
abc *b = new abc();
memcpy((void *)&b, (void *)&a, sizeof(abc));
std::cout << a->gullu.data() << std::endl;
std::cout << b->gullu.data();
return 0;
}
Debugging it, I found that after doing memcpy the content of object 'a' becomes garbage.
After a's construction,
(gdb) p *a $1 = {gullu = {static npos = 4294967295, _M_dataplus = {> = {<__gnu_cxx::new_allocator> = {}, }, _M_p = 0x804ea18 "dhfghdf"}, _M_string_length = 7, {_M_local_buf = "dhfghdf\000\000\000\000\000\000\000\000", _M_allocated_capacity = 1734764644}}}
After b's construction
(gdb) p *b $2 = {gullu = {static npos = 4294967295, _M_dataplus = {> = {<__gnu_cxx::new_allocator> = {}, }, _M_p = 0x804ea38 ""}, _M_string_length = 0, {_M_local_buf = '\000' , _M_allocated_capacity = 0}}}
After memcpy
(gdb) p *a $4 = {gullu = {static npos = 4294967295, _M_dataplus = {> = {<__gnu_cxx::new_allocator> = {}, }, _M_p = 0x666468 }, _M_string_length = 2572404, {_M_local_buf = "t@'\000\030Ùÿ¿I\215\004\b\001\000\000", _M_allocated_capacity = 2572404}}}
(gdb) p *b $5 = {gullu = {static npos = 4294967295, _M_dataplus = {> = {<__gnu_cxx::new_allocator> = {}, }, _M_p = 0x804ea18 "dhfghdf"}, _M_string_length = 7, {_M_local_buf = "dhfghdf\000\000\000\000\000\000\000\000", _M_allocated_capacity = 1734764644}}}
I am using a thirdparty library which seems to be doing a memcpy, which was working with previous compiler and not working with gcc 5.1 because of this issue
Can someone help me with this?