Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Strange behaviour when implementing strcat in C

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,

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

  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?

>Solution :

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 string literals cannot be written to.

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!
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading