View Full Version : strcpy c/c++
I wanna know why this isnt working:
char * temp;
char * data;
data = "a-b-c-";
print(data) //prints a-b-c
print(temp) //not printed, program doesnt get past the strcpy
how else can i make a copy of data?
ralph l mayo
09-26-2007, 09:51 PM
There's nothing remotely C++ about that sample, it's just C.
It's not working because you're not giving the compiler enough information to manage memory for you.
When you say char* foo; You're making a pointer to one character. Add more characters than that to it at your own peril, because they'll overwrite whatever happens to be sitting there after the pointer, causing undefined behavior. Trying to do what you're doing actually seems to work pretty well on my system apart from triggering ~60 memory errors in valgrind. Some part of your data is getting stepped on when strcpy moves data into unallocated space after temp*
You need to either declare the pointers with array syntax with a length or initialize the pointer with a malloc with the length.
Powered by vBulletin® Version 4.2.2 Copyright © 2017 vBulletin Solutions, Inc. All rights reserved.