C语言使用strcat拼接字符串时出现异常前缀的问题咨询
问题:C语言程序输出出现随机奇怪前缀
期望输出
152 = 2 + 5*10 + 1*100
实际异常输出
E:\c>e:\c\hello.exe X152 = 2 + 5*10 + 1*100 E:\c>e:\c\hello.exe X?52 = 2 + 5*10 + 1*100 E:\c>e:\c\hello.exe X?52 = 2 + 5*10 + 1*100
问题代码
#include <stdio.h> #include <string.h> int mypow(int s, int times); //only a pow function return a int int main(void) { int a; char str[80]; char result[80]; int cur; int input = 152; int len = 3; sprintf(str, "152 = "); strcat(result, str); for (a = 0; a < len; a++) { cur = input % 10; input = input / 10; if (a == 0) { sprintf(str, "%i", cur); strcat(result, str); sprintf(str, " + "); strcat(result, str); } else if (a < len - 1) { sprintf(str, "%i*%i", cur, mypow(10, a)); strcat(result, str); sprintf(str, " + "); strcat(result, str); } else { sprintf(str, "%i*%i", cur, mypow(10, a)); strcat(result, str); } } puts(result); return 0; }
异常原因分析
核心问题:
result数组未初始化
C语言中,局部数组如果没有显式初始化,内存空间会保留栈上的随机垃圾数据。而strcat函数的工作逻辑是从目标字符串的末尾'\0'终止符位置开始拼接新内容。由于result未初始化,内存中没有合法的'\0',strcat会从数组起始位置开始扫描内存,直到找到某个随机出现的'\0'才开始拼接内容。这就导致拼接前的随机垃圾字符被当成了result的一部分,最终输出时出现奇怪前缀。修复方案
在使用strcat前,先将result初始化为空字符串:char result[80] = "";或者手动设置终止符:
char result[80]; result[0] = '\0';
内容的提问来源于stack exchange,提问作者sunboy_zgz
相关产品推荐
相关产品推荐

