Monday, 20 February 2012

What is the difference between the functions strdup() and strcpy()? C Programming

strcpy function: copies a source string to a destination defined by user. In strcpy function both source and destination strings are passed as arguments. User should make sure that destination has enough space to accommodate the string to be copied.
'strcpy' sounds like short form of "string copy".
Syntax:
strcpy(char *destination, const char *source);
Source string is the string to be copied and destination string is string into which source string is copied. If successful, strcpy subroutine returns the address of the copied string. Otherwise, a null pointer is returned.
Example Program:
#include<stdio.h>
#include<string.h>

int main() {
char myname[10];
//copy contents to myname
strcpy(myname, "
blosumsdotnet.blogspot.com");
//print the string
puts(myname);
return 0;
}

Output:
blosumsdotnet.blogspot.com
Explanation:
If the string to be copied has more than 10 letters, strcpy cannot copy this string into the string 'myname'. This is because string 'myname' is declared to be of size 10 characters only.
In the above program, string "nodalo" is copied in myname and is printed on output screen.
strdup function: duplicates a string to a location that will be decided by the function itself. Function will copy the contents of string to certain memory location and returns the address to that location. 'strdup' sounds like short form of "string duplicate"
Syntax:
strdup (const char *s);
strdup returns a pointer to a character or base address of an array. Function returns address of the memory location where the string has been copied. In case free space could not be created then it returns a null pointer. Both strcpy and strdup functions are present in header file
Program: Program to illustrate strdup().
#include
<stdio.h>
#include
<string.h>

#include<stdlib.h>

int main() {
char myname[] = "blosumsdotnet.blogspot.com";
//name is pointer variable which can store the address of memory location of string
char* name;
//contents of myname are copied in a memory address and are assigned to name
name = strdup(myname);
//prints the contents of 'name'
puts(name);
//prints the contents of 'myname'
puts(myname);
//memory allocated to 'name' is now freed
free(name);
return 0;
}

Output:
blosumsdotnet.blogspot.com
blosumsdotnet.blogspot.com

Explanation:
String myname consists of "interviewmantra.net" stored in it. Contents of myname are copied in a memory address and memory is assigned to name. At the end of the program, memory can be freed using free(name);