C++ string stack overflow

By | November 8, 2016

收到一個 Win32 C++ program,發覺 input 大 file 時,執行途中會掛掉。查看 source code 後估計好大機會是因為 stack overflow。

改左幾句,把 wstring 改做 wchar_t 及改埋相關的 functions 便解決了 stack overflow 問題。原因是「新」C++ STL 是會把短 string 放 stack,長 string 才放 heap,咁做是為左 performance 考量,要知道 stack 快過 heap 好多。但超大量短 string 就會做成 stack overflow。結果修改後,便能正常運行。

點解用 wchar_t 唔用 char,是因為要處理中文,char 要用 UTF-8 編號才可放非英文字元。在近乎全中文下,UTF-8 比 UTF-16 不但運算慢,也需要更多存儲空間。

下一步就是把 program 移植到 Linux,寫左個 cmake script,用 #define 隔開同 OS 相關的 API call,當中主要是 filesystem 相關的。結果在 Linux compile 無問題了,之後 implement 返在 POSIX 相應的 functions 便可。