2013-10-24 7 views
3

我使用unordered_map在C++一個HashMap的時候,但每當我嘗試存儲任何東西在那裏,我得到:浮點異常存儲東西放到unordered_map

Floating point exception: 8

任何人都可以指出哪些錯誤是?下面是我如何初始化我的地圖(table_entry只是一個結構):

std::tr1::unordered_map<unsigned short, table_entry*> forwarding_table;

然後我把一個條目中這樣做:

unsigned short dest_id = 0;  
table_entry *entry = (table_entry *)malloc(sizeof(table_entry)); 
forwarding_table[dest_id] = entry; 

我的結構的定義是:

typedef struct table_entry { 
    unsigned short next_hop; 
    unsigned int cost; 
} table_entry; 

就我的編譯器版本而言,當我運行g++ -v時,得到:

Configured with: /private/var/tmp/llvmgcc42/llvmgcc42-2336.11~182/src/configure --disable-checking --enable-werror --prefix=/Applications/Xcode.app/Contents/Developer/usr/llvm-gcc-4.2 --mandir=/share/man --enable-languages=c,objc,c++,obj-c++ --program-prefix=llvm- --program-transform-name=/^[cg][^.-]*$/s/$/-4.2/ --with-slibdir=/usr/lib --build=i686-apple-darwin11 --enable-llvm=/private/var/tmp/llvmgcc42/llvmgcc42-2336.11~182/dst-llvmCore/Developer/usr/local --program-prefix=i686-apple-darwin11- --host=x86_64-apple-darwin11 --target=i686-apple-darwin11 --with-gxx-include-dir=/usr/include/c++/4.2.1 Thread model: posix gcc version 4.2.1

+0

如果'table_entry'不是POD類型,那麼你的時間就會很糟糕。 – chris

+0

剛看了POD類型,我相信它是。爲了清楚起見,我將添加我的結構定義。 – Penguinator

+0

@chris,只要存儲一個指針應該沒問題,不管當你嘗試使用它時會發生什麼壞事。 –

回答

1

我最近遇到了同樣的問題,使用各種實例std::unordered_map<>。但是,我只能在地圖全局化爲共享對象時重現問題。如果地圖在程序中聲明爲全局,或者在函數中聲明爲地圖,則問題不會顯示。

(注:我使用GCC 4.9.4,32位模式,以-std = C++ 11)

似乎在堆上分配的std::unordered_map<>解決我的問題。也許它會解決你的?考慮更換:

std::tr1::unordered_map<unsigned short, table_entry*> forwarding_table; 

std::tr1::unordered_map<unsigned short, table_entry*>* forwarding_table; 

,然後更新的forwarding_table適當用途。

+0

多一點Google搜索會顯示另一個解決方法:在首次使用之前插入reserve()調用似乎可以解決問題。參見[GCC Bugzilla](https://gcc.gnu.org/bugzilla/show_bug.cgi?id=61143) –