简体   繁体   中英

Stange seg fault when using += with strings

There must be something obvious I don't realize about C++ with this one.

load(string & filename){

 string command;
 char delimiter = '/';
 size_t delimiterPos = filename.rfind(delimiter);
 string directory = string(filename.c_str(),delimiterPos);
 command = "import path ";

  //want to add directory to end of command
  string temp = command + "hello!"; // This works
  command.append(directory); //This works!
  command += directory;  //This seg faults!
  ...
}

in GDB when I "print" filename at the beginning of the function I get: (const string &) @0x9505f08: {static npos = 4294967295, _M_dataplus = {> = {<__gnu_cxx::new_allocator> = {}, }, _M_p = 0x950a8e4 "../config/pythonFile.py"}}

What the heck, how is filename formatted incorrectly, such that .append() works and += doesn't?! Something strange in the overloaded function += in C++?

g++ version 3.4.6

Maybe it has to do with how you are constructing "directory" here

 size_t delimiterPos = filename.rfind(delimiter);
 string directory = string(filename.c_str(),delimiterPos);

Is rfind somehow failing? If rfind failed, it would return std::npos as specified here . I'm not sure what the behavior would be if you passed npos into the string constructor. It may be platform dependent.

This doesn't answer why "append" would work and "+=" would crash. You may also have some kind of heap corruption (maybe caused by the npos and C string passed into the constructor above) and maybe when += is called new memory needs to be allocated. Append for whatever reason may not need to allocate new memory.

In any case, it would be wise to add a check for npos.

I can not reproduce your problem. The file below works here with g++:

#include <string>
#include <iostream>

using namespace std;

int main(int, char**)
{
 string filename("a/b/c/d");

 string command;
 char delimiter = '/';
 size_t delimiterPos = filename.rfind(delimiter);
 string directory = string(filename.c_str(),delimiterPos);
 command = "import path ";

  //want to add directory to end of command
  string temp = command + "hello!"; // This works
  command.append(directory); //This works!
  cout << command << endl;

  command += directory;  //This seg faults!
  cout << command << endl;

}

Output:

$ g++ -o t t.cpp
$ ./t
import path a/b/c
import path a/b/ca/b/c

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM