glibc detected (memory error) on inserting into std::map
I have the following code:
struct VRfile{
char sessionID[10];
char file[20];
int first;
};
std::map (int ,struct VRfile *) maps;
struct VRfile *vrinfo = (struct VRfile*)malloc (sizeof(struct VRfile*));
strcpy(vrinfo->sessionID, sessionId.c_str());
strcpy(vrinfo->file, filename.c_str());
socketmap.insert(std::pair(int , struct VRfile *) (thisfd,vrinfo));
I'm getting an 开发者_运维百科error at the socketmap.insert(std::pair(int , struct VRfile *) (thisfd,vrinfo));
line:
Error: *** glibc detected *** memory corruption: 0x080aa7b0 ***
/lib/libc.so.6[0x6222dd]
/lib/libc.so.6(__libc_malloc+0x67)[0x623e97]
/usr/lib/libstdc++.so.6(_Znwj+0x27)[0x45d7ab7]
backtrace:
0 0x002eb402 in __kernel_vsyscall ()
1 0x005e0df0 in raise () from /lib/libc.so.6
2 0x005e2701 in abort () from /lib/libc.so.6
3 0x0061928b in __libc_message () from /lib/libc.so.6
4 0x006222dd in _int_malloc () from /lib/libc.so.6
5 0x00623e97 in malloc () from /lib/libc.so.6
6 0x045d7ab7 in operator new(unsigned int) () from /usr/lib/libstdc++.so.6
Then it points to the line of code I have mentioned above. Can nyone tell me why this is happening?
You're not allocating enough space for your structure—you're only allocating a pointer's worth (4 or 8 bytes, depending on your pointer size), when in fact you should be allocating somewhere on the order of 36 bytes (specifically, sizeof(VRfile)
. So, you're stomping on the heap by writing random values into it (a so-called heap overrun), which is messing up the data structures used by malloc
to track memory. When it detects this corruption, it throws its hands up and terminates your program.
However, since this is C++ and not C, you should really be using operator new
instead of malloc
to allocate dynamic memory. You don't have to deal with the size of the memory you're allocating, it's implicit in the variable type. Secondly, there's no reason to always say struct VRfile
instead of just VRfile
—that's only needed in plain C code (not C++), and only when there isn't a proper typedef
(which there usually is).
So, just write this:
VRfile *vrinfo = new VRfile;
And of course, when you delete your map (or remove any element from it, for that matter), make sure to delete each value in it to avoid leaking memory. For example:
// This could also be implemented using a functor and std::for_each
for(std::map<int, VRfile*>::iterator iter = maps.begin(); iter != maps.end(); ++iter)
delete iter->second;
maps.clear();
In your malloc
call, you're allocating enough memory for a pointer to a VRfile
instead of a VRfile
(probably just a typo).
VRfile *vrinfo = (VRfile*)malloc(sizeof(VRfile));
Note also that in C++ you don't need to use struct
when referencing the type.
精彩评论