BigBen59
BigBen59

Reputation: 123

string size stays zero

I made this function

the input string is something like this "the little fox was white" I'm calling this function myword=my_copy_from(input,11,3) I was hopping I would get the word "fox" back but when I used the debugger I saw that the size of back is staying 0 bytes.

Why is that??? thanks

    // start of my_copy_from //
     string my_copy_from(string in,short start,short len)
     {
    string back ;
    short i;

    for (i=0 ; i<len; i++)
    {
      back[i]=' ';
      back[i]=in[start+i];


    }

    return back;
}
   // end of my_copy_from //

Upvotes: 0

Views: 111

Answers (4)

Kingsley Chen
Kingsley Chen

Reputation: 385

Because the back now is empty if you don't assign any string-value neither reserve some space explicitly, and that means each access to back via operator[] is illegal. Despite no boundary-check performed, access via operator[] beyond the index scope results in undefined behavior, and it is lucky your compiler just ignore it.

To solve this problem, you can explicitly reserver some space for back

string s;
s.reserve(len); // or s.resize(len);

or use function append

string s;
s.append(in, start, len);

Actually, there already is a function named substr in string doing the same thing.

string s = in.substr(start, len); 

Upvotes: 0

avakar
avakar

Reputation: 32685

Indexing a string beyond its end results in undefined behavior. You're lucky that the program didn't crash.

You must resize the string in advance.

back.resize(len);

However, it might be easier to use the substr member function.

return in.substr(start, len);

Upvotes: 4

shivakumar
shivakumar

Reputation: 3407

Use substr builtin function. no need of for loop.

string my_copy_from(string in,short start,short len)
     {
    string back ;
    short i;

  /*  for (i=0 ; i<len; i++)
    {
      back[i]=' ';
      back[i]=in[start+i];


    }*/
    back = in.substr(start,len);

    return back;
}

Upvotes: 0

user93353
user93353

Reputation: 14049

string back;

creates a string without any memory allocated. So your for loop is undefined behaviour. It could as well have crashed. doing back[i] on a zero sized string doesn't make sense.

First allocate memory for your string using resize.

back.resize(len);

before your for loop. Then your program makes sense.

Inserting a space before putting the actual character also makes no sense.

Upvotes: 0

Related Questions