I have code which goes like this. Could you tell me why it is not behaving as I would expect it to be?
/*
* test.cpp
*
* Created on: Dec 6, 2012
* Author: sandeep
*/
#include<iostream>
#include<string.h>
using namespace std;
int main()
{
int i=0;
string s="hello A B:bye A B";
char *input;
input=new char(s.size());
for(i=0;i<=s.size();i++)
input[i]=s[i];
char *tokenized1[2],*tokenized2[3];
tokenized1[0]=strtok(input,":");
tokenized1[1]=strtok(NULL,":");
i=0;
char *lstring;
while(i<2)
{
lstring=new char(strlen(tokenized1[i]));
memcpy(lstring,tokenized1[i],strlen(tokenized1[i])+1);
cout<<tokenized1[0]<<" "<<tokenized1[1]<<endl;
tokenized2[0]=strtok(lstring," ");
tokenized2[1]=strtok(NULL," ");
tokenized2[2]=strtok(NULL," ");
char c=tokenized2[0][0];
cout<<c<<endl;
cout<<tokenized2[0]<<" "<<tokenized2[1]<<" "<<tokenized2[2]<<endl;
i++;
}
}
and the output is this.
hello A B by
h
hello A B
hello A B by
b
by
There are some junk values at the end of 1st, 4th and 6th line of output.
Why tokenized1[1] got altered when I I did memcopy of tokenized1[0]? and how to solve this?
There’s a couple of bugs in the following
newcall. You need to use square brackets; also, the argument is off by one.Without the square brackets, your are allocating space for one character. As a result, the
memcpy()writes past the allocated memory.edit: I just noticed the other
new, which will also need to be fixed:Finally,
s[i]reads past the end of the string in:There could well be other bugs, not to mention memory leaks…