Thread: strcpy without new

  1. #1
    Registered User
    Join Date
    Jan 2006
    Posts
    61

    strcpy without new

    Hi
    For example i have a class, in that class there is a function that assign a string.
    Code:
    void func(char * name1)
    {
    	name1 = new char[strlen(this->name)+1)]
    	strcpy(name1, this->name);
    	delete[] name;
    }
    I can also write like this:

    Code:
    void func(char * name1)
    {
    	strcpy(name1, this->name);
    
    }
    I looked and see that 2 of them are valid.
    So May be any problem in the second example. I mean is this wrong or may cause memory leak? Or Are 2 of them same
    Thanks

  2. #2
    The superhaterodyne twomers's Avatar
    Join Date
    Dec 2005
    Location
    Ireland
    Posts
    2,273
    Why don't you use std::string?

  3. #3
    Deathray Engineer MacGyver's Avatar
    Join Date
    Mar 2007
    Posts
    3,210
    The first one is a waste of resources. You're passing it a pointer. Try to think of this as passing the pointer by value. A copy of the address of the string where you want to copy this->name to is sent to the function. This means that name1 points to some block of memory.

    Now when the function starts, you assign name1 to point to some other random block of memory through new, and you copy this->name to it, but then you delete the memory. Why? name1 is no longer valid, and on top of it, the original pointer you passed it to has not been updated with the value.

    I'm curious as to why you're not using C++ strings. Assuming you're not able to use them (ie. an assignment won't let you), the proper way to do something like this, would be to write a function with something similar to one of the following prototypes:

    Code:
    char *copy(void); /* returns a dynamically created char * using new */
    Code:
    void copy(char **); /* Alters what the parameter points to, and copies to it*/
    Code:
    void copy(char *, size_t); /* Copies the string up to the amount of specified chars to the string passed */

  4. #4
    Registered User
    Join Date
    Jan 2006
    Posts
    61
    Thank you.
    I wrote my codes wrong in my first post.
    Sorry.
    I understood.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. A Full Program to analyze.
    By sergioms in forum C Programming
    Replies: 2
    Last Post: 12-30-2008, 09:42 AM
  2. Strcpy
    By Godders_2k in forum C Programming
    Replies: 17
    Last Post: 12-12-2007, 12:34 PM
  3. Where is strcpy() defined? (Can't find in string.h ect)
    By Zero_Point in forum C++ Programming
    Replies: 6
    Last Post: 04-03-2006, 05:14 PM
  4. Question about strcpy
    By Kevinmun in forum C Programming
    Replies: 4
    Last Post: 11-02-2005, 11:00 PM
  5. strcpy
    By Luigi in forum C++ Programming
    Replies: 17
    Last Post: 02-16-2003, 04:11 PM