简体   繁体   中英

strange return behavior in strcat()

void mystrcat(char* to, const char* from) {
    while (*to) to++;
    while (*from) *to++ = *from++;
    *to = '\0';
}

int main() {
    char addthis[]= "rest of the sentence";
    char start_of[] = "going to add ";


    mystrcat(start_of, addthis);

    cout << "after strcat(): " << start_of<< endl;
}

even if i replace the function mystrcat to follows, behaviour is same.

char* mystrcat(char* to, const char* from) {
    while (*to) to++;
    while (*from) *to++ = *from++;
    *to = '\0';
    return to;
}

strange for me, when i call mystrcat i dont assign to a char* still no compiler's complain. what am i missing here? follow up can u optimize my code with void return type if anyway

The string start_of is declared to be only long enough to hold the string it is initialized with. So attempting to append to it writes past the end of the array. This invokes undefined behavior .

You need to make the array large enough to hold the concatenated string.

char start_of[50] = "going to add ";

You don't need to always assign the return value to some variable if you are returning from a function in C. The other functions like printf scanf also returns value but they need not give any error if you are not assigning them to some variable while calling.

Also, as a side note, your mystrcat function is running on undefined behavior. You are passing it two char array and appending to the first char array itself when it doesn't have any further space allocated to it. So, you should change it.

You should declare the char array of first argument that you are passing to the function to be long enough to be able to hold the data after concatenation. You can change your program as follows -

void mystrcat(char* to, const char* from) {
    while (*to) to++;
    while (*from) *to++ = *from++;
    *to = '\0';
}

int main() {
    char addthis[]= "rest of the sentence";
    char start_of[100] = "going to add ";


    mystrcat(start_of, addthis);

    cout << "after strcat(): " << start_of<< endl;
}

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