关于使用malloc函数动态申请内存空间的问题
先放代码再说好描述
程序代码:#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void loopinput(void);
char * findstr(char *,char *);
int main(void)
{
loopinput();
return 0;
}
void loopinput(void)
{
char str1[50],str2[50];
char * p;
printf("please input two strings.\n");
while( scanf("%s %s",str1,str2)==2 )
{
char fchr;
getchar();
p=findstr(str1,str2);
printf("p=%s\n",p);
printf("input y to continue,anther word to quit.\n");
fchr=getchar();
if(fchr!='y')
break;
printf("please input two strings.\n");
}
}
char * findstr(char * str1,char * str2)
{
int i;
bool flag=false;
int len1=strlen(str1);
int len2=strlen(str2);
char * pc;
pc=(char *)malloc((len1)*sizeof(char));
if(pc==NULL)
exit(-1);
for(i=0;i<len2-len1+1;i++)
{
strncpy(pc,str2+i,len1);
pc[len1]='\0';
if( strcmp(str1,pc)==0 )
{
flag=true;
break;
}
}
if(flag==true)
return pc;
else
return NULL;
}这是一个查找字符串的函数输入第一参数指定的字符串 并在第二个参数指定的字符串中查找
查找到返回指针 未找到返回空指针
代码中我使用malloc函数申请strlen(str1)*sizeof(char)个内存空间
但实际中会多出许多内存空间
而这些未初始化的多余的内存空间将导致不能正常判断pc与str1是否相等
因此我使用了pc[len1]='\0' 这种无奈的方法
我想问问为什么malloc函数申请的空间大小和我期望的不一样
还有我这个函数没有释放pc 不知道在什么地方是否








内容不能为空。。。


