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

如何在C语言中拆分char指针字符串并修复栈溢出错误

问题修复:字符串拆分导致栈溢出的解决方法

错误原因分析

你的代码触发栈溢出检测,核心问题有两个:

  • time_buff数组越界写入:time_buff的大小是9(索引范围0-8),但你直接用t=14到22作为time_buff的索引,比如time_buff[14]已经超出数组的内存范围,破坏了栈上的其他数据,触发了系统的栈保护机制。
  • date_buff缺少字符串终止符:date_buff[13]的大小刚好容纳"Friday 6 June"的13个字符,但C语言字符串必须以'\0'结尾,否则后续操作(比如打印)会读取超出数组范围的内存,属于未定义行为。

修复后的代码方案

方案1:基于原代码修正索引与数组大小

#include <stdio.h>
#include <string.h>

int main()
{
    char *message = "Friday 6 June 11:08:04 2020";
    char time_buff[9] = {0};  // 11:08:04共8个字符,加'\0'刚好9位
    char date_buff[14] = {0}; // "Friday 6 June"共13个字符,加'\0'需要14位

    // 复制日期部分
    for(int d=0; d<13; d++){
        date_buff[d] = message[d];
    }
    // 数组初始化全0,最后一位自动为'\0',无需手动添加

    // 复制时间部分:将message的14-22位映射到time_buff的0-8位
    for(int t=14; t<23; t++){
        time_buff[t - 14] = message[t];
    }

    // 打印拆分结果
    printf("date = %s\n", date_buff);
    printf("time = %s\n", time_buff);

    return 0;
}

方案2:更鲁棒的通用拆分方式(无需硬编码索引)

如果字符串格式可能存在变化(比如日期部分长度不同),可以通过查找空格位置实现灵活拆分:

#include <stdio.h>
#include <string.h>

int main()
{
    char *message = "Friday 6 June 11:08:04 2020";
    char date_buff[32] = {0};
    char time_buff[16] = {0};

    // 遍历找到第三个空格的位置(时间部分的起始点)
    int space_count = 0;
    char *ptr = (char*)message;
    while(*ptr != '\0' && space_count < 3){
        if(*ptr == ' '){
            space_count++;
        }
        ptr++;
    }
    char *time_start = ptr;

    // 复制日期部分:从开头到第三个空格前
    strncpy(date_buff, message, time_start - message - 1);
    date_buff[time_start - message - 1] = '\0';

    // 复制时间部分:取前8个字符(11:08:04)
    strncpy(time_buff, time_start, 8);
    time_buff[8] = '\0';

    printf("date = %s\n", date_buff);
    printf("time = %s\n", time_buff);

    return 0;
}

关键注意事项

  • C语言字符串必须以'\0'结尾,数组大小要预留足够空间存放终止符。
  • 数组索引必须在合法范围内(0到数组长度-1),越界写入会破坏内存,触发栈溢出或其他未定义行为。

内容的提问来源于stack exchange,提问作者Mahmoud Abdel-Rahman

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 00:35:13