关于“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;
}
Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐