[問題] new int array的方法

作者: TampaBayRays (光芒今年拿冠軍)   2018-11-19 20:39:07
開發平台(Platform): (Ex: Win10, Linux, ...)
FreeBSD 11.2
CentOS 7.5.1804
編譯器(Ex: GCC, clang, VC++...)+目標環境(跟開發平台不同的話需列出)
VS code
額外使用到的函數庫(Library Used): (Ex: OpenGL, ...)
問題(Question):
我想要new一個int陣列用來當作pipe使用,
舉例來說假設指令是ls | cat | cat,
那我會有一個int pipenum=2,再執行
int *pfd = new int[2*pipenum],然後分別執行
pipe(pfd) pipe(pfd+2),再來使用這兩個pipe傳資料
但是有時候在new array的時候會有下面這個錯誤訊息
然後程式就被terminate了
請問是我new array的方式有什麼問題嗎?
還是跟OS有關呢?
感謝
預期的正確結果(Expected Output):
new 一個int array
錯誤結果(Wrong Output):
terminate called after throwing an instance of 'std::bad_array_new_length'
what(): std::bad_array_new_length
Abort trap (core dumped)
可能的原因我google了一下有:
1. If the array size is less than zero.
2. If the array size is greater than an implementation-defined limit.
3.If the number of elements in the initializer list exceeds the
number of elements to initialize.
1是不可能的,所以我猜是2,那這樣算是OS的問題嗎?
程式碼(Code):(請善用置底文網頁, 記得排版,禁止使用圖檔)
vector <string> commands=SplitString(line," | ");
pipenum=commands.size()-1;
cout<<"here"<<endl;
int *pfd = new int [2*pipenum];
cout<<"there"<<endl;
line是我的input command
結果只有印出here,所以我想應該是這行的問題
作者: ilikekotomi (Young)   2018-11-19 20:56:00
沒有完整可再現的code只能猜是pipenum有問題cppreference寫說有三個情況會跳這個exception這行code有可能問題是數字太大或是負的要不要先嘗試把pipenum在here那邊印出來
作者: Fenikso (薪水小偷)   2018-11-19 21:12:00
就印出來看看啊 說不定是split寫壞讓size()有時候傳回0
作者: ilikekotomi (Young)   2018-11-19 21:17:00
因為不知道spilt line怎麼做的要不要把line 和command都印出來看看可以的話希望提供整份可以執行的code和input data剛剛想到有沒有請朋友多跑幾次看看 也許真的是OS問題就可以快點重灌電腦了
作者: steve1012 (steve)   2018-11-20 01:00:00
你覺得new 要了太多個element的size 你有沒有算過你大概new 了多少個?這不用猜測吧不確定你其他地方寫了什麼 但瞄了一下line要是空字串你能確保不會返回零嗎?若是你覺得這不會發生 你可以在new array之前throw 或assert 不是零去排除1.的狀況自己猜/印不太可靠
作者: sarafciel (Cattuz)   2018-11-20 17:19:00
string.find要求字串全符合 你的input全部都是用" | "做連接嗎 還是有" |"、" |"或"|"的case
作者: steve1012 (steve)   2018-11-21 01:32:00
不要信任自己某件事不會發生 讓程式告訴你

Links booklink

Contact Us: admin [ a t ] ucptt.com