Go Back   CodingForums.com > :: Computing & Sciences > Computer Programming

Before you post, read our: Rules & Posting Guidelines

Reply
 
Thread Tools Rate Thread
Enjoy an ad free experience by logging in. Not a member yet? Register.
Old 09-26-2007, 08:28 PM   PM User | #1
klam
New Coder

 
Join Date: Jan 2007
Posts: 12
Thanks: 1
Thanked 0 Times in 0 Posts
klam is an unknown quantity at this point
strcpy c/c++

I wanna know why this isnt working:

Code:
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
how else can i make a copy of data?
klam is offline   Reply With Quote
Old 09-26-2007, 08:51 PM   PM User | #2
ralph l mayo
Regular Coder

 
ralph l mayo's Avatar
 
Join Date: Nov 2005
Posts: 951
Thanks: 1
Thanked 31 Times in 29 Posts
ralph l mayo is on a distinguished road
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.
ralph l mayo is offline   Reply With Quote
Reply

Bookmarks

Jump To Top of Thread


Thread Tools
Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off

Forum Jump


All times are GMT +1. The time now is 06:06 AM.


Advertisement
Log in to turn off these ads.