string型老是溢出,不知道怎么解决

C++运行时,老是报string subscript out of range

#include<iostream>
#include<ctime>
#include<string>
using namespace std;
const int MAX=200;
string Key;
void bitcode(string src,string obj,int len)
{
    for(int i=0;i<len;i++)
        obj[i]=src[i]^Key[i];
    obj[len]=0;
}
void makeKey(int len)
{
    for(int i=0;i<len;i++)
        Key[i]=rand()%10+'0';//随机生成数字
}
int main()
{
    string srcstr="123456";
    string objstr; 
    int length=srcstr.length();
    srand(time(NULL));
    makeKey(length);
    bitcode(srcstr,objstr,length);
    cout<<"密文:"<<objstr<<endl;
    bitcode(objstr,srcstr,length);
    cout<<"原文:"<<srcstr<<endl;
    system("pause");
    return 0;
}

需要先分配内存;遇到问题,多cout看是哪里出问题

#include<iostream>
#include<ctime>
#include<stdlib.h>
#include<string>
using namespace std;
const int MAX=200;
string Key;
string bitcode(string src,string obj,int len)
{
    for(int i=0;i<len;i++) {
        obj[i] = '0' + (src[i]^Key[i]);
    }
    return obj;
    //obj[len]=0;
}
void makeKey(int len)
{
    Key = string(len, '0');
    for(int i=0;i<len;i++)
        Key[i]=rand()%10+'0';//随机生成数字
}
int main()
{
    string srcstr="123456";
    int length=srcstr.length();
    string objstr(length, '0'); 
    srand(time(NULL));
    makeKey(length);
    objstr = bitcode(srcstr,objstr,length);
    cout<<"密文:"<<objstr<<endl;
    srcstr = bitcode(objstr,srcstr,length);
    cout<<"原文:"<<srcstr<<endl;
    //system("pause");
    return 0;
}