关于“Stack around the variable ‘‘ was corrupted.”的错误原因分析【strcat()函数】

关于“Stack around the variable '' was corrupted.”的错误原因分析

错误说明

博主在复习C语言的过程中,调用 字符串拼接函数 strcat() 时。发生了如题的错误,但是程序可以正常输出,字符串拼接结果是没有问题的。就感觉很奇怪。

代码如下:

#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
#include<string.h>

int main()
{
	char str2[] = "Sheldon!!!";
	char str1[] = "Don't be a fool!"; 
	
	printf("The lenth of str1 is %d, the size of str1 is %d.Because the \'\\0\'!\n", strlen(str1), sizeof(str1));
	//put them together ,we use strcat() or strncat()
	strcat(str2, str1);
	printf("%s\n",str2);
	/*char str3[80];
	strcpy(str3,str1);
	printf("%s\n", str3);*/
	return 0;
}

拼接的结果是正确的,但是会弹出错误窗口。
在这里插入图片描述

在这里插入图片描述

错误分析与解决方法

查阅资料发现,Stack around the variable ‘’ was corrupted 是指 “某变量周围的堆栈区被破坏了”,更详细的分析可以参照这篇博客

分析自己的代码,发现是因为在进行字符串声明的时候,没有明确指示字符串的大小,这时候计算机自动识别并分配存储空间,之后要对字符串进行拼接,就会导致原先开辟的存储空间是不够用的,所以就会破环原变量周围的堆栈区。
我采用的解决办法就是明确大小,并留出足够的大小来提供字符串的拼接。这样再运行就完美通过啦!

int main()
{
	char str2[40] = "Sheldon!!!";
	char str1[20] = "Don't be a fool!"; 
	
	printf("The lenth of str1 is %d, the size of str1 is %d.Because the \'\\0\'!\n", strlen(str1), sizeof(str1));
	//put them together ,we use strcat() or strncat()
	strcat(str2, str1);
	printf("%s\n",str2);
	return 0;
}
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值