Thread: strdup

  1. #1
    Registered User
    Join Date
    Feb 2009
    Posts
    329

    strdup

    Hi,

    An exercise from my book is to implement my own version of the strdup function, which returns a copy of a string allocated on the freestore.

    This is my code:
    Code:
    char *strdup(const char* ch)
    {
    	const char* p = ch;
    	int size = 0;
    	while(*p){
    		++size;
    		++p;
    	}
    
    	int index = 0;
    	char* name = new char[size];
    	while(*ch){
    		name[index] = *ch;
    		cout << *ch;
    		++ch;
    		++index;
    		
    	}
    
    	return name;
    		
    }
    My question is that when I create name, I allocate memory on the free store. When I return this, I take it that it is still allocated on the freestore and when whatever has called it finishes using it, that is when I call delete[]? Is that correct?

    BTW, the exercise states that I cannot use any standard library function, hence my own version of size.

    Thanks.

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,661
    Looks good to me - your analysis is correct.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  3. #3
    Registered User
    Join Date
    Feb 2009
    Posts
    329
    Quote Originally Posted by Salem View Post
    Looks good to me - your analysis is correct.
    Thanks, I'm on the right track then!

  4. #4
    The larch
    Join Date
    May 2006
    Posts
    3,573
    BTW, the exercise states that I cannot use any standard library function, hence my own version of size.
    I would write my own strlen and strcpy then...

    It also appears that you might not be allocating space for and copying the null terminator. (It would be more immediately visible if you used your own versions of strlen and strcpy with the exact same behavior.)

    And I guess a strdup user would assume that the buffer was allocated with malloc (they need to know the details)...
    I might be wrong.

    Thank you, anon. You sure know how to recognize different types of trees from quite a long way away.
    Quoted more than 1000 times (I hope).

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Strdup
    By Ducky in forum C++ Programming
    Replies: 4
    Last Post: 04-01-2010, 12:52 PM
  2. strdup against array? segfaults
    By schurt in forum C Programming
    Replies: 9
    Last Post: 03-12-2010, 11:21 AM
  3. strcpy, strdup
    By shibu in forum C Programming
    Replies: 6
    Last Post: 09-13-2006, 12:29 PM
  4. strdup
    By hankspears in forum C Programming
    Replies: 4
    Last Post: 05-09-2002, 02:02 PM
  5. function: strdup()
    By cjtotheg in forum C Programming
    Replies: 3
    Last Post: 02-02-2002, 10:08 AM