Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

656
Views
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
over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

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.)

over 4 years ago · Santiago Trujillo Report

0

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";
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!