DimeCadmium
DimeCadmium

Reputation: 11

Seg fault doing new vector<string>

The following code gets a seg fault on the last line:

   HookAct *act = new HookAct;
    act->hkAct = HookAct::PRINT;
    act->params = new vector<string>;

Valgrind tells me:

==15551== Process terminating with default action of signal 11 (SIGSEGV)
==15551== Access not within mapped region at address 0x0
==15551== at 0x5927026: std::string::assign(char const*, unsigned long) (in /usr/lib/libstdc++.so.6.0.10)
==15551== by 0x725424A: test (test.cpp:10)

Does anyone have any idea why it is doing this?

FYI, here's the [current, temporary] definition of HookAct:

struct HookAct {
    enum {
        PRINT
    } hkAct;
    vector<string> *params;
};

Upvotes: 0

Views: 365

Answers (2)

sbi
sbi

Reputation: 224059

As Brian said, the error message points at str::string being initialized with NULL, which is forbidden. However, your code looks like written by someone who comes from Java or C# and is used to mindlessly new everything. In C++, however, automatic storage is preferred.

If you change your code to this

struct HookAct {
    enum {
        PRINT
    } hkAct;
    vector<string> params;
    HookAct() : hAct(HookAct::PRINT), params() {}
};

no manual dynamic memory managing is necessary anymore:

HookAct hookAct;

Upvotes: 3

Brian R. Bondy
Brian R. Bondy

Reputation: 347216

The code you pasted is fine.

I think your problem is probably adding a NULL string to the vector act->params.

Upvotes: 1

Related Questions