You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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 of strncat_s is the total size of the destination buffer, not the length you want to append. You passed 7, but your dest buffer is 50 bytes long. Worse, the initial string in dest ("This is destination") is already way longer than 7 characters—this triggers strncat_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: max and Len are 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 for strncat_s's safety features.
  • size_t is the standard type for string lengths and counts—using char here 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:
    size_t available_space = sizeof(dest) - strlen(dest) - 1;
    strncat_s(dest, sizeof(dest), src, (append_length < available_space) ? append_length : available_space);
    
    This prevents writing past the end of the buffer even if the source is longer than expected.

内容的提问来源于stack exchange,提问作者Jordan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 09:37:19