C++: vector<string> *args = new vector<string>(); causes SIGABRT

旧街凉风 提交于 2019-11-29 15:24:37

The int count = sizeof(_arguments); seems pretty dubious.

sizeof gives you size in bytes, not number of elements an array (except in the case where each element is exactly one byte, i.e. char).

Cheers & hth.,

sbi

There is no real error in this code, although the style suggests that you urgently need a good C++ book.

As @James said in his comment to the question, it is almost certainly wrong to use a dynamically allocated vector object, and it's certainly wrong to not to keep it in a smart pointer.
If you've also done this elsewhere in your code, you very likely have messed up the heap, which is the only case I can think of when new would crash.

Okay, it turns out the problem was NOT with the vector allocation, but rather inside the for() loop. Replacing it with a proper do/while loop fixed it. GDB was simply confused about where the error was and stuck it on the vector line... ugh. Not surprising given the use of the STL though.

Also, to those who say allocating a vector dynamically can mess up the heap - why? This makes no sense; I don't care if I allocate every single object dynamically; doing that should not cause problems. Mixing heap and stack objects has caused me a lot of problems in the past; the only way I can get things to work consistently is using all heap objects.

If someone can explain how stack and heap objects can coexist, though, I'd be happy to hear it, because they've never worked together for me. Objective-C makes perfect sense, while C++'s nonsensical treatment of objects almost always causes problems. Unfortunately we're required to use C++, so it leaves me without a lot of choice...

Possibly something else has corrupted the heap before you do this call. Have you tried running under valgrind or equivalent?

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!