关于free函数报错问题

来源:互联网 发布:struts2 json result 编辑:程序博客网 时间:2024/05/21 03:18
 

  在VC 6.0 下编译的C程序,源代码如下:

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

int main()
{
 char *s, *t;
 char *r; 

 s = "Hello ";
 t = "world!/n";
 r = (char *)malloc(strlen(s) + strlen(t));
 strcpy(r, s);
 strcat(r, t);
 printf(r);

 free(r);
 return 0;
}

 

  编译和连接都没有问题,但是在运行的时候出现:

Debug Error!

DAMAGE:after Normal block (#43) at 0x003707A8

 

  初步判断应该是在调用函数strcpy和strcat时,对r进行了修改,产生越界,从而释放内存失败。

检查以后果然发现在malloc(strlen(s) + strlen(t))时少分配了一个长度;(strlen函数去掉了字符串末尾的'/0'字符),导致在调用strcat的时候长度不够,因而重新动态分配了内存地址。

  将函数改为:

int main()
{
 char *s, *t;
 char *r; 

 s = "Hello ";
 t = "world!/n";
 r = (char *)malloc(strlen(s) + strlen(t) + 1);
 strcpy(r, s);
 strcat(r, t);
 printf(r);

 free(r);
 return 0;
}

就不再报错了!

 

 

 
原创粉丝点击