[问题] 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