简体   繁体   中英

Writing my own strcopy Function in C using pointers

I am trying to create my own string copy function in C. Copying the text works, however extra characters are added to the destination string at the end and I don't know why. I would be very happy to get an answer.

Here is my code:

#include <stdio.h>
#include <string.h>
 
void copy(char *dst, char *src) {
    int src_len = strlen(src);
    char *src_strtng = &src[0];
    char *dst_strtng = &dst[0];
    for (int i = 0; i < src_len; i++) {
        *dst_strtng++ = *src_strtng++;
    }
    printf("%s\n", dst);
}
 
int main() {
    char srcString[] = "We promptly judged antique ivory buckles for the next prize!";
    char dstString[strlen(srcString)];
    copy(dstString, srcString);
}

create my own str copy function in C.

Missing null character termination

This is OP's key issue, lack of appending a null character to dst .

Only need to traverse src once

Rather than strlen() in copy() , just look for '\0' . *1

Does not return a char *

Save the destination pointer.

Missing const for data referenced by src

Pedantic concern: str should act as if char was unsigned char *2

char *copy(char* dst, const char* src) {
  unsigned char *udst = (unsigned char *) dst;
  const unsigned char *usrc = (const unsigned char *) src;

  do {
    *udst++ = *usrc;
  } while (*usrc++);
  return dst;
}

Allocate enough space for the length of a string and a null character

strlen() returns the length of a string . That does not include the final null character .

int main() {
  char srcString[] = "We promptly judged ...";
  char dstString[strlen(srcString) + 1]; // Add 1
  copy(dstString,srcString);
}

*1 C's strcpy() is char *strcpy(char * restrict s1, const char * restrict s2);

Note the restrict . This implies access via the pointer is not affected by other code. Eg source string and destination will not overlap.

// Better as
char *copy(char* restrict dst, const char* restrict src) {

OP's use of strlen() in copy() is a good first step to handle overlapping memory (see following), but strcpy() does not need to handle that - suggest copy() not deal with overlap.

char *copy_handle_overlap(char* dst, const char* src) {
  return memmove(dst, src, strlen(src) + 1);
}

*2 C string functions have:

For all functions in this subclause, each character shall be interpreted as if it had the type unsigned char (and therefore every possible object representation is valid and has a different value).

This is important for the rare non-2's complement to distinguish +0 from -0 .

Non-2's complement support expected to be dropped with C2X.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM