申请堆空间时出现的错误

来源:互联网 发布:win10安装不了软件 编辑:程序博客网 时间:2024/05/16 15:08
#include <stdio.h>#include <stdlib.h>#include <string.h>struct foo{int a;//4char b[6];//8char *p;//4char c[0];};#define EXPAND_MEM15int main(){printf("size =%u\n",sizeof(struct foo));struct foo *pf = (struct foo*)malloc(sizeof(struct foo)+EXPAND_MEM*sizeof(int));
<span style="white-space:pre"></span>/* 之前代码
<span style="white-space:pre"></span>*<span style="white-space:pre"></span><span style="font-family: Arial, Helvetica, sans-serif;">struct foo *pf = (struct foo*)malloc(sizeof(struct foo)+EXPAND_MEM);//这样后面赋值的时候就会越界</span><span style="font-family: Arial, Helvetica, sans-serif;"></span>
<span style="white-space:pre"></span>*/if(!pf){printf("there is not enough memory!\n");exit(EXIT_FAILURE);}strcpy(pf->b,"hello");printf("pf->b :%s,pf :%p\n",pf->b,pf);int i;for(i=0;i<EXPAND_MEM;i++){*(pf->c +i)=i;}#if 1printf("pf->b :%s,pf :%p\n",pf->b,pf);printf("pf->c=[");for(i=0;i<EXPAND_MEM;i++){printf("%d ",*((pf->c)+i));}printf("]\n");#endifpf->p = (char *)calloc(EXPAND_MEM,sizeof(char));if(!(pf->p)){printf("there is not enough memory!\n");exit(EXIT_FAILURE);}strcpy(pf->p,"I LOVE Linux");printf("pf->p %s\n",pf->p);free(pf->p);free(pf);return 0;}


0 0
原创粉丝点击