Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 2 of 2

Thread: strcpy c/c++

  1. #1
    New Coder
    Join Date
    Jan 2007
    Posts
    12
    Thanks
    1
    Thanked 0 Times in 0 Posts

    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?

  • #2
    Regular Coder ralph l mayo's Avatar
    Join Date
    Nov 2005
    Posts
    951
    Thanks
    1
    Thanked 31 Times in 29 Posts
    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.


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •