Home > Blockchain >  Strange behaviour when implementing strcat in C
Strange behaviour when implementing strcat in C

Time:04-05

I'm trying to implement the strcat function myself. Here's my code:

char *my_strcat(char *dst, const char* src) {
    char *tmp = dst;
    while(*tmp) {
        tmp   ;
    }
    while(*tmp   = *src  );
    return dst;
}

However, when I try to test this function, I get only the src string. (i.e. I'm expecting to get dst src, but the returned value is the same as src)

As we can tell from the code, in the first while loop, I'm trying to move tmp pointer to the end of dst. However,

  1. I tried to add a printf in the first while loop, nothing is printed out, which indicates that it didn't even entered the loop.

  2. Then I tried to used if (*tmp == '\0') print something, and found that *tmp == '\0' is true.

But I'm pretty sure that tmp is a non-empty string, so *tmp should point to the first character of the string (I think). So I'm feeling confused about it. Can anyone tell why this happens and how can I fix it?

Edit: The calling code is

char *subpath = "";
subpath = my_strcat(subpath, path);

path is a const char* read from the command. Do I need to assign the value back to subpath? Or just calling my_strcat is enough?

CodePudding user response:

There are two problems here:

char *subpath = "";
subpath = my_strcat(subpath, path);
  • subpath points to a string of length 0, there is not enough space to append anything.
  • subpath points to a string literal and writing into string literals is undefined behaviour, on modern desktop platforms your program usually crashes.

You want something like this:

char subpath[100] = "";
char *foo;
foo = my_strcat(subpath, path);

or just

char subpath[100] = "";
my_strcat(subpath, path);

or

char subpath[100] = "Hello ";
my_strcat(subpath, "world!");
printf("%s\n", subpath);  // prints  Helllo World!
  • Related