0
votes

My program is segfaulting a very puzzling way. It happens in the std::string library code, so I assume that my program is overwriting that std::string code somewhere else. The segfault happens when I attempt to assign a char* to a std:string in a automatic variable:

struct MyStruct
{
    std::string name;
    int winch_ndx;
    ...
};

void MyFunction(const char * nodeName)
{
    MyStruct dataL;
    dataL.name = nodeName;  <-- segfault
    ...
}

Since dataL is an automatic variable, other portions of the code could not be overwriting the memory it occupies, so I guess the library code itself is being overwritten with the value 0x6C2FD8 (see below). What is puzzling about this is that Valgrind doesn't detect the original invalid write at all. I don't know how else this 0x6C2FD8 could be introduced into the std::string code. Any insight would be appreciated.

The Valgrid output and my valgrind command follows.

==17112== Process terminating with default action of signal 11 (SIGSEGV)

==17112== Bad permissions for mapped region at address 0x6C2FD8

==17112== at 0x9B07D87: __exchange_and_add (atomicity.h:47)

==17112== by 0x9B07D87: __exchange_and_add_dispatch (atomicity.h:80)

==17112== by 0x9B07D87: std::string::_Rep::_M_dispose(std::allocator const&) [clone .part.12] (basic_string.h:246)

==17112== by 0x9B07F78: _M_dispose (char_traits.h:243)

==17112== by 0x9B07F78: std::string::_M_mutate(unsigned long, unsigned long, unsigned long) (basic_string.tcc:487)

==17112== by 0x9B083ED: std::string::_M_replace_safe(unsigned long, unsigned long, char const*, unsigned long) (basic_string.tcc:684)

==17112== by 0x613ADA: MyFunction (comm.cpp:1108)

valgrind  --gen-suppressions=all --error-markers=BEGIN_MARK,END_MARK --free-fill=FF --malloc-fill=FF --trace-malloc=yes --trace-children=yes --track-origins=yes --read-var-info=yes --partial-loads-ok=no --log-file=vg2.out my_program 
1
Try this: if(nodeName) { dataL.name = std::string(nodeName); } - erip
You would probably get the same segfault if you tried to access nodeName some other way. Why would you be using valgrind anyway? - David Schwartz
are you compiling with warnings treated as errors? i suspect a stack corruption (warnings will help you finding the stack corruption, so should valgrind... but meh) - user1708860
Using your code, the same segfault occurs. nodeName is not NULL and contains a valid null-terminated string. I'm using Valgrind because the symptoms of the crash suggest that I am writing to memory that is out-of-bounds from some unknown part of my program. As to warnings, do you mean compiling with -Wall? - Kurt

1 Answers

3
votes

Check nodeName for being NULL, also check that nodeName actually points to a '\0' terminated string ...