Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why I am getting wrong output for source string when I am implementing strcat()?

Here I tried implementing strcat function in C. Problem is that when I am printing the source string it is showing me "hyam" not "shyam"

#include <stdio.h>
#include <string.h>

char *fun(char *target, const char *source) {
    printf("%s\n", source);
    int x = strlen(target);
    while (*source != '\0') {
        *(target + x++) = *source++;
    }
    *(target + x) = '\0';
    return target;
}

int main() {
    char target[] = "ram";
    char source[] = "shyam";
    fun(target, source);
    printf("%s\n", target);
    printf("%s", source);
    return 0;
}

Here in last line of output hyam is shown but it should be shyam.

shyam
ramshyam
hyam
like image 347
Ankit Bhardwaj Avatar asked Jan 24 '26 07:01

Ankit Bhardwaj


2 Answers

Your target array is too small - it needs at least nine elements (the length of both strings plus a terminating zero).

Writing outside target has undefined behaviour, but in practice, it looks like your arrays happen to be laid out end to end, like this:

 |r|a|m|\0|s|h|y|a|m|\0|
 ^        ^
 |        | 
target   source

and then you concatenate, going past the end of target into source:

 |r|a|m|s|h|y|a|m|\0|\0|
 ^       ^
 |       | 
target  source

which makes it look like an 's' has disappeared.

(Note that this is undefined, so anything can happen. You can't rely on this behaviour, unless the documentation for your compiler says that it's fine and should do this. Which it most likely won't.)

like image 114
molbdnilo Avatar answered Jan 25 '26 20:01

molbdnilo


The problem is the array target defined with char target[] = "ram"; is too short to accommodate appending the contents of the source string. You must make target larger, at least 9 bytes, 8 for the characters and one more for the null terminator:

char target[9] = "ram";
like image 24
chqrlie Avatar answered Jan 25 '26 19:01

chqrlie



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!