-1

I have this simple code splitting a string made of equalities separated by ampersands:

std::string cmd = "par1=1&par2=ciao&par3=1.2e4"

std::stringstream ss(cmd);
std::string argdef;
std::vector<std::string> pairs(0);

while (std::getline(ss, argdef, '&'))
  pairs.push_back(argdef);

I correctly collect three equalities into the vector 'pairs', but the while loop continues beyond the end of the stream, and I get a segmentation fault. How to avoid this?

Hybridslinky
  • 131
  • 1
  • 13
  • [Cannot reproduce.](http://coliru.stacked-crooked.com/a/35cfe24f53a60b49) – aschepler Aug 10 '17 at 01:45
  • Pretty sure getline will blow right through null terminators. Try adding an `&` to the end of your string? Never mind...stringstream should be handling eof for your. – zzxyz Aug 10 '17 at 01:51

2 Answers2

1

You program needs a ; at the end of the line that set the cmd value.

The source code you show has no problem (if you add ;). We can compile it without warning and it works well, if we add somes lines to make it an autonomous program:

#include <iostream>
#include <string>
#include <sstream>
#include <vector>

int main(int ac, char **av) {
  std::string cmd = "par1=1&par2=ciao&par3=1.2e4";

  std::stringstream ss(cmd);
  std::string argdef;
  std::vector<std::string> pairs(0);

  while (std::getline(ss, argdef, '&')) {
    std::cout << argdef << std::endl;
    pairs.push_back(argdef);
  }

  return 0;
 }

For instance, the compilation works with no warning on Linux OpenSuSE LEAP 42.1 with g++/gcc 4.8.5 (the source file is named x.cpp), and the output is correct (as you can see, I've added a line to log the content of argdef, and it looks correct) :

% g++ -Wall -o x x.cpp
% ./x
par1=1
par2=ciao
par3=1.2e4
%

So everything is fine here.

Explanation of the root cause of your segfault error:

  • either the ; you had forgotten on the first line make the program not compile at all, and the binary that you were running was an old one, with bugs;
  • or you have anything else in your program that leads to the segmentation fault.

Anyway, the source code shown here is correct.

Alexandre Fenyo
  • 4,526
  • 1
  • 17
  • 24
  • The ';' is missing only in my question. Actually the posted code is in a function taking the string as an argument. That is the only difference, otherwise the code is the same. I'm cross compiling with mingw 64 bit on cygwin. It compiles without warnings, but at runtime I get the segmentation fault. I'll try to check other parts of my code, but it's strange, because it stopped working exactly when I've added the string splitting function. – Hybridslinky Aug 10 '17 at 11:57
0

This error occurs if you are taking input using cin before using getline in your code. Take all the inputs using getline in your program and your segmentation fault would disappear.