Unexpected behavior from strcpy/strtok?

Hey folks, I have a program that is meant to read in lines from a text file, and split them into tokens around ", " using strtok(). So for instance, "WSAD, 1234" should be split into "WSAD" and then "1234". However, when I execute my code, I get a runtime error. I have spent quite a while looking at my code, but I still don't understand the problem. Could a kind soul look into it and tell me what I'm doing wrong? My code is below:


using namespace std;

int main()
string filename,obj;
cout<<"Please enter filename: ";

ifstream file;

{ cout<<"Error in opening file"<<endl;}

char* copy;
char* un, *deux;

strcpy(copy, obj.c_str());//error occurs around or after here
un=strtok(copy,", ");
deux=strtok(NULL,", ");


return 0;
}//end of program

strcpy(copy, obj.c_str());//error occurs around or after here

This is an attempt to copy the letters from obj into the memory space pointed at by the pointer copy. Where is the pointer copy pointing?

Well, you created it like this:
char* copy;
so it starts out just pointing at some random memory somewhere, that could be anywhere, and that's it.

So you're trying to write over some random piece of memory somewhere that doesn't belong to your program, and the OS spots this and stops the program, as it should.

You have to make that pointer actually point at memory that is yours to write on.
Variable copy was not initialized

char* copy;

So this pointer points nowhere.
I see. Alright, any suggestions on a suitable way to initialize the pointer? I'm not allowed to use arrays of any kind for any reason, because this is for an assignment and that was a restriction my lecturer implemented.
Since we're coding like it's 1980, we could use malloc.

After reading in the string, you could do something like:
char* copy = (char*) malloc(obj.length()); which will definitely be enough space to strtok into.

I'd prefer new:
char* copy = new char[obj.length()]; but that would probably be taken as an array.

Don't forget to free anything you malloc.

Last edited on
malloc worked. Thank you! Though now I'm curious, why do you say it's like the 80s?
Because C++ turned up with new in the eighties, and also brought with it a number of nicer ways to tokenise string objects than using the C function strtok.
Topic archived. No new replies allowed.