Seg fault doing new vector<string>
The following code gets a seg fault on the last line:
HookAct *act = ne开发者_StackOverflow社区w 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;
};
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;
The code you pasted is fine.
I think your problem is probably adding a NULL
string to the vector act->params
.
精彩评论