malloc函数分配得到的空间是存储在堆区的。
系统推出后是不会被释放的,必须由程序员自己用free释放。
#include
#include
#include
#include
#include
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
#include
#include
#include
#include
#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)
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()返回的是字符串不含结尾符的字符个数。