开发者

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

Pretty self explanatory. Here's the method that's causing the SIGABRT on the 'new vector' line:

vector<string> * Task::arguments() {
    vector<string> *args = new vector<string>(); // CAUSES SIGABRT
    int count = sizeof(_arguments);
    for (int x = 0; x < count; x++) {
        string argument(_arguments[x]);
        args->push_back(argument);
    }
    return args;
}

Note that elsewhere I call that exact line without any issues. Here is the list of includes in the Task class:

#include <vector>
#include <unistd.h>
#include <string>
using namespace std;
#include <sys/types.h>
#include <sys/wait.h开发者_如何学Go>
#include <signal.h>

Any thoughts?


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.


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.,


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?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜