Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 2 of 2
Thread: strcpy c/c++
09-26-2007, 09:28 PM #1
- Join Date
- Jan 2007
- Thanked 0 Times in 0 Posts
I wanna know why this isnt working:
char * temp; char * data; ........... data = "a-b-c-"; print(data) //prints a-b-c strcpy(temp,data); print(temp) //not printed, program doesnt get past the strcpy
09-26-2007, 09:51 PM #2
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.