Why would an empty std::map seg fault on the first insert?

I've got a weird C++ problem which make no sense to me.  I have a class containing a std::map<> data member, which I fill during the initialization process.  On my Mac (OSX 10.5.8, GCC 4.0.1), the map is filled perfectly fine, and the data is accessed when the job runs with no problem.  When I build and run on Linux (RHEL 5.6, GCC 4.1.2), the std::map<> itself seg-faults the first time something is inserted.

I've tried the insert with both table[key] = value and with table.insert(std::pair<>(key,value)) and I get the identical result. For some reason, std::map<>::insert_unique() doesn't recognize that the map is empty, and it tries to decrement one position before begin(), triggering the seg-fault.

Am I doing something wrong? Do I need to explicitly zero the map (the constructor should do that itself, shouldn't it?)?


15 answers
sort by: active | newest | oldest
Mar 27, 2012. 12:03 PMrobnich says:
I had a similar situation with std:set. Looking at the assembler output from the compiler, mine was a compiler bug. The compiler used the wrong offset to access a member variable a few functions deep. You might try a newer version of gcc.
Jul 29, 2011. 5:34 AMorksecurity says:
Is the insert happening immediately after the map's creation?

If not, I'd suspect a wild pointer problem somewhere, overwriting the map...
Jul 29, 2011. 7:37 AMorksecurity says:
My C++ skills are limited (last time I used it intensively was before the std:: library was created!), so I'm probably going to have to bow out. Good luck.

(Sanity check: You aren't doing something odd like using a placement constructor, right?)
Jul 29, 2011. 9:20 AMsteveastrouk says:
Ah, "Properly" = "as I expected" != "what the standard probably says".......

Personally, I think C++ is a horrible language, but that's just me.

Steve
Jul 30, 2011. 12:45 PMsteveastrouk says:
Even Fortran's gone OOP in the lastest versions AFAIK.

Steve
Jul 30, 2011. 2:14 PMsteveastrouk says:
So how come you get stuck with C++ ?
Jul 29, 2011. 12:35 AMsteveastrouk says:
I don't see why the constructor should necessarily initialise the map. What happens if you try zeroing it ?

How do you instantiate the map in the code ?

Steve
Jul 29, 2011. 8:23 AMsteveastrouk says:
I think it depends on the exact syntax when its instantiated.
http://en.cppreference.com/w/cpp/container/map/map

Pro

Get More Out of Instructables

Already have an Account?

close

PDF Downloads
As a Pro member, you will gain access to download any Instructable in the PDF format. You also have the ability to customize your PDF download.

Upgrade to Pro today!