xpi0t0s's Avatar, Join Date: Aug 2004
Um, no. It may appear to work fine in this simple example, but in fact the code suffers from a buffer overflow.

Since you don't specify the size of dest, the compiler deduces it from what's between the braces. {1} is just one item long, so dest is actually of type char[1], which is probably the single most pointless declaration in C, because you have to use pointers and by using array terminology people would be expecting a string here, not a single character, and you only have space for a terminating NULL. If you want a single char, declare dest as "char dest;" and drop the array syntax.

So dest[1..3], which are written to in strcopy REGARDLESS of the actual length of the string in src[], are not part of the dest array; they belong to someone else, and you've just overwritten their memory for them.

Why are you only copying 4 bytes regardless of the size of the string in src? As I said to another poster, this is more of a memcpy function than a strcpy. strcpy should take string semantics into consideration, i.e. it should be written according to the fact that a string is a number of characters terminated with a zero byte. So the end of the copy loop should end after copying the zero byte, not after a fixed number (unless you're implementing strncpy).
back from retirement's Avatar, Join Date: Nov 2008
Yes.....it will change I think, because you have not specified the size of dest initially....else you would have to allocate it dynamically....
Still I wait for the expert's opinion to be absolutely confirm....
manju154's Avatar, Join Date: Oct 2011
Newbie Member
#include <stdio.h>

void stringcopy(char *, char *);
int main()
    int i;
    char src[] = "hai this patil";
    char *dest = (char*)malloc(strlen(src)+1);

    stringcopy(dest , src);
    printf("source  = %s\n",src);
    printf("destination = %s\n",dest);

void stringcopy(char *t , char *s)
    while ((*t = *s) !=0) {

Last edited by shabbir; 18Oct2011 at 11:54.. Reason: Code blocks