C语言strncat_s拼接失败仅输出目标串,求程序修改建议
Alright, let's figure out why your strncat_s call isn't working as expected and fix the code properly.
The main issues in your code:
- Wrong buffer size passed to
strncat_s: The second argument ofstrncat_sis the total size of the destination buffer, not the length you want to append. You passed7, but yourdestbuffer is 50 bytes long. Worse, the initial string indest("This is destination") is already way longer than 7 characters—this triggersstrncat_s's safety checks, which prevents the append from happening (it might even truncate the original string or abort the program depending on your compiler's implementation). - Syntax error: You forgot a semicolon after
char Len=8—this will cause a compile error before the program even runs. - Unused variables:
maxandLenare defined but never used; they're just cluttering up the code.
Fixed code:
#include <stdio.h> #include <string.h> #include "safe_str_lib.h" int main () { char src[50], dest[50]; // Use size_t for string length variables (standard practice) size_t append_length = 8; strcpy(src, "This is source"); strcpy(dest, "This is destination"); // Correct strncat_s usage: // 1. Destination buffer // 2. Total size of destination buffer (use sizeof to avoid hardcoding) // 3. Source string // 4. Max number of characters to append from source strncat_s(dest, sizeof(dest), src, append_length); printf("Final destination string : |%s|", dest); return 0; }
Key explanations:
- Using
sizeof(dest)instead of a hardcoded number ensures we always pass the correct total buffer size, which is critical forstrncat_s's safety features. size_tis the standard type for string lengths and counts—usingcharhere is risky because it's a small, potentially signed type that can cause overflow issues.- If you want to ensure the final string doesn't exceed a specific length (instead of just appending 8 characters), you'd calculate the available space first:
This prevents writing past the end of the buffer even if the source is longer than expected.size_t available_space = sizeof(dest) - strlen(dest) - 1; strncat_s(dest, sizeof(dest), src, (append_length < available_space) ? append_length : available_space);
内容的提问来源于stack exchange,提问作者Jordan
相关产品推荐
相关产品推荐

