0

I use the following function to split a string into arrays (not very efficient but i just wanted to test something):

    string* split(string a)
    {
      int i,j;
      j=0;
      string res[255];
      for(i=0;i<=a.size()-1;i++)
      {
      if(a[i]==',')
      {
        j++;
        continue;
      }
     res[j]+=a[i];
    }
     return res;
    }

And if i use this function like this for example:

  string* f;
  string a = "meho,hohrepere";
  f = split(a);
  cout<<f[0]<<endl;

It will throw a very weird error (i am used to get this if i access an array outside it's predefined size) ...basically a very long list of smiley faces and weird characters...

What i do not understand is why....because it seems to only throw this error if the "," is on the 3rd or 4th position in the string (no matter what the string is)...

What am i doing wrong?

Edit: This question doesn't have anything to do with Can a local variable's memory be accessed outside its scope? while my question was why it happened just in those specific cases....

Community
  • 1
  • 1
SpiderLinked
  • 363
  • 1
  • 6
  • 14
  • Note that `i<=a.size()-1` is just `i – chris Jul 14 '14 at 15:48
  • ...yea...i've changed the -1 after <=...so i've forgot to remove it...but still...this does not answer my question...why do i only get this error in those specific cases?..btw "or something"...isn't a very helpfull response... – SpiderLinked Jul 14 '14 at 15:50
  • It doesn't matter which cases act weirdly and which don't. It's undefined behaviour in all cases. Undefined means just what it says. This is explained in the linked question (quote: "**anything can happen**"). And fine, return a `std::vector`. Use `push_back` to add a new string as you go. – chris Jul 14 '14 at 16:04
  • ....what generates that undefined behavior? – SpiderLinked Jul 14 '14 at 19:47
  • `res` ceases to exist after the function ends. A pointer to any part of it becomes a dangling pointer. – chris Jul 14 '14 at 19:51

0 Answers0