MESSAGE
DATE | 2005-01-26 |
FROM | Ruben Safir
|
SUBJECT | Re: [hangout] Simple C question
|
On Tue, 2005-01-25 at 16:03, Billy wrote: > Inker, Evan wrote: > > Check this out > > > > strcopy.c > > > > /* strcopy.c written by detour-at-metalshell.com > > * > > * example of a string copying function. > > * > > * http://www.metalshell.com/ > > * > > */ > > > > #include > > #include > > > > void strcopy(const char *, char *); > > > > int main() { > > char string1[] = "This is string1"; > > char string2[] = "This is string2"; > > > > strcopy(string1, string2); > > printf("String2: %s", string2); > > } > > > > void strcopy(const char * str1, char * str2) { > > int x = 0; > > > > /* change the size of string2 to the size of string1 */ > > realloc(str2, sizeof(str1)); > > > > do { > > str2[x] = str1[x]; > > } while (str1[x++] != '\0'); > > > > } > > > This program is incorrect. > YOU CANNOT overwrite the contents of string2.
Why not? It is not a string literal.
> It is also illegal to > realloc() a pointer which was not obtained by malloc(). > also, realloc is free to move the block. you have to use its return > value to update the pointer. There's just so much wrong... > > I DON'T RECOMMEND learning from this example. >
I agree. There is no reason to rewrite strncpy
Ruben
____________________________ NYLXS: New Yorker Free Software Users Scene Fair Use - because it's either fair use or useless.... NYLXS is a trademark of NYLXS, Inc
|
|