C语言malloc()的一个问题——堆越界的一个错误。

malloc函数分配得到的空间是存储在堆区的。

系统推出后是不会被释放的,必须由程序员自己用free释放。

#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <string.h>
#include <malloc.h> 
int main()
{
	int address;
char *q;
	char *p=(char *)malloc(sizeof(char)*10);
q=strcpy(p,"chenhuijie is a good boy");

	printf("p:%s(%p),q:%s(%p)\n",p,p,q,q);

	address=(int)p;

	printf("int:%p",address);

	printf("the string is %s\n",(char *)address);

	free(p);

	

	//p++;


}

在调试时,单步调试至free(p)时。发生如下错误。


原来是发生了堆越界了。

	char *p=(char *)malloc(sizeof(char)*10);
q=strcpy(p,"chenhuijie is a good boy");

分配的堆空间为10个byte。多出来的字符被放置在10之后的内存中。一不小心发生了越界。才出现了这个堆被破坏的错误。


为了提高健壮性,应改为如下:

#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <string.h>
#include <malloc.h> 

#define m_len 30
int main()
{
	int address;
	
    char *q="chenhuijie is a good boy";
	char *p=(char *)malloc(sizeof(char)*m_len);


	assert((strlen(q)+1)<m_len);

    q=strcpy(p,q);

	printf("p:%s(%p),q:%s(%p)\n",p,p,q,q);

	address=(int)p;

	printf("int:%p",address);

	printf("the string is %s\n",(char *)address);

	free(p);

	

	//p++;


}

主要是增加了长度检查的功能。为什么
strlen(q)+1)
这样呢?是因为strlen()返回的是字符串不含结尾符的字符个数。

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值