高手进来帮忙看个程序

来源:百度知道 编辑:UC知道 时间:2024/09/20 07:13:23
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void main (void)
{
char *p,*p1,*p2;
p=(char *)malloc(80);
printf ("input a string:\n");
gets(p);
p1=p;
while(*p1!=0)
{
if((*p1>='a'&&*p1<'x')||(*p1>='A'&&*p1<'X'))
*p1+=3;
else if((*p1>='x'&&*p1<='z')||(*p1>='X'&&*p1<='Z'))
*p1-=23;
*p1++;
}
p2=p;
while(*p2!=0)
{
printf ("%c",*p2);
p2++;
}
printf ("\n");
FILE *fp;
fp=fopen("D:\\test.txt","w+");
if(fp==NULL)
{printf ("fail");exit(0);}
while(*p!=0)
{
printf ("%c",*p);
fprintf(fp,"%c",*p);
p++;
}
fclose(fp);
free (p1);
free (p2);
free (p);
}

原因是:
你只用malloc申请一次内存,所以,只能释放一次
另外,你申请的是什么地址,就应该释放什么地址,不能这样:
p=malloc(...);
p++;
free(p);
因为p已经被你改变了(自加了)

程序修改如下:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

void main (void)
{
char *p,*p1,*p2;

p=(char *)malloc(80);
printf ("input a string:\n");
gets(p);
p1=p;
while(*p1!=0)
{
if((*p1>='a'&&*p1<'x')
||(*p1>='A'&&*p1<'X'))
{
*p1+=3;
}
else if((*p1>='x'&&*p1<='z')
||(*p1>='X'&&*p1<='Z'))
{
*p1-=23;
}
*p1++;
}
p2=p;
while(*p2!=0)
{
printf ("%c",*p2);
p2++;
}
printf ("\n");

FILE *fp;
fp=fopen("D:\\test.txt","w+"