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

C语言printf打印字符串异常:CS50学习中的问题排查与解决

C语言printf字符串打印异常问题排查

问题背景

学习哈佛大学CS50课程C语言第二讲时,使用printf的%s格式符重复打印字符串出现异常。授课老师说明%s会依次对应打印每个额外参数,但实际输出与预期不符。

最初代码与异常输出

代码

#include <stdio.h>

int main(void) {
   char firstname[5] = "Bruce";
   char lastname[5] = "Wayne";

   printf("Hi, %s!\nI am your virtual butler. I will call you Master %s from now on.\nWelcome to %s Manor!", firstname, lastname);
}

实际输出

Hi, BruceWayne!
I am your virtual butler. I will call you Master Wayne from now on.
Welcome to  q��U Manor!

预期输出

Hi, Bruce!
I am your virtual butler. I will call you Master Wayne from now on.
Welcome to Wayne Manor!

尝试修复与结果

更新1:修复数组长度定义

将数组定义改为自动推导长度,避免结束符缺失问题,但输出仍有乱码。

修改后代码

#include <stdio.h>

int main(void) {
   char firstname[] = "Bruce";
   char lastname[] = "Wayne";

   printf("Hi, %s!\nI am your virtual butler. I will call you Master %s from now on.\nWelcome to %s Manor!", firstname, lastname);
}

输出

Hi, Bruce!
I am your virtual butler. I will call you Master Wayne from now on.
Welcome to  ���(V Manor!

更新2:匹配printf格式符与参数数量

在printf的参数列表中补充第三个lastname参数,输出符合预期。

修改后的printf语句

printf("Hi, %s!\nI am your virtual butler. I will call you Master %s from now on.\nWelcome to %s Manor!", firstname, lastname, lastname);

问题原因分析

  1. 数组长度不足导致字符串越界:最初的char firstname[5] = "Bruce"中,"Bruce"包含5个字符,但C语言字符串需要末尾的\0结束符标记字符串结束。长度为5的数组无法容纳该结束符,导致firstname和lastname在内存中连续存储,printf打印firstname时越界读取到lastname的内容,出现BruceWayne的异常。
  2. printf格式符与参数数量不匹配:原代码中有3个%s格式符,但仅传入2个参数。第三个%s会读取栈上的随机垃圾数据,导致乱码。更新1修复了数组结束符问题,但未解决参数数量不匹配的核心问题,因此仍有乱码;更新2补充了第三个参数,格式符与参数一一对应,输出恢复正常。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 19:44:59