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

C语言字符串拼接触发buffer overflow错误,附问题代码示例

C程序缓冲区溢出问题排查修复

根因定位

缓冲区溢出是destination数组的空间分配错误直接导致的:
当你使用char destination[] = "curl -X GET https://dex.binance.org/api/v1/account/";定义数组时,编译器会严格按照后面字符串常量的实际长度分配空间,仅刚好能存储该字符串本身(包括末尾的\0结束符),没有预留任何多余空间用于拼接后续的Address字符串。调用strcat时会直接向destination数组的边界外写入数据,触发缓冲区溢出报错。

修复方案

核心逻辑是给destination数组分配足够的存储空间,同时增加边界校验避免溢出,修复后的参考代码如下:

#include "ring.h"
#include "string.h"
#include "stdlib.h"

RING_FUNC(ring_bingetaccount)
{
    char Address[100] = {0};
    // 给destination分配足够的空间:前缀长度+Address最大长度+冗余余量
    char destination[256] = "curl -X GET  https://dex.binance.org/api/v1/account/";
    // Check Parameters Count
    if (RING_API_PARACOUNT != 1) {
        RING_API_ERROR(RING_API_MISS1PARA);
        return;
    }
    // Check Parameters Type
    if ( ! RING_API_ISSTRING(1) ) {
        RING_API_ERROR(RING_API_BADPARATYPE);
        return;
    }
    // 安全复制输入字符串,避免Address溢出
    strncpy(Address, RING_API_GETSTRING(1), sizeof(Address)-1);
    // 校验拼接后不会超出destination的容量
    if (strlen(destination) + strlen(Address) >= sizeof(destination)) {
        RING_API_ERROR("input parameter is too long");
        return;
    }
    strcat(destination, Address);
    int status = system(destination);
}

你也可以用更安全的snprintf函数直接完成拼接,减少出错概率:

// 替换strcpy、strcat部分的代码
snprintf(destination, sizeof(destination), "curl -X GET  https://dex.binance.org/api/v1/account/%s", RING_API_GETSTRING(1));

额外注意事项

  • 该实现直接将用户输入拼接到系统命令中,存在命令注入风险,如果输入参数包含;、|等特殊字符,会导致任意命令执行,生产环境使用需要先对输入参数做特殊字符转义。
  • 尽量避免用strcpy、strcat这类无边界检查的字符串操作函数,优先用strncpy、strncat、snprintf等带长度参数的安全函数。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 15:27:00