函数调回指针的内存释放,(30分)请评价我编写的一个程序,
比如说你申明一个函数char *string_cmp(char *str, const char *str1)
在其中你为要返回的指针用malloc申请了一快内存地址,那你该如该将其释放呢?
上次的回答我不是很满意,请大家看看我写的一个程序吧。
函数调回指针的内存释放(25分)
程序代码:#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MAX 256
static char *findchars; //函数find_char的返回指针,返回被找到的字符,
char *find_char(char const *source, char const *chars);
//参数要搜索的字符串指针和给定字符集合
//带回找到的字符的集合的指针
int main (void)
{
char *main_findchars;
if ((main_findchars = (char *)malloc(sizeof(MAX))) == NULL)
{
printf("malloc error!\n");
exit(1);
}
printf("we will find if there are members of the chars 'a,g9cd'");
printf("in the string we input.\n");
main_findchars = find_char("gfdgadgasd^dfe;(hdf8fgjgh,uy,i,oipujikthetwerqw", "a,g9cd");
printf("the chars we find from the strings is %s\n", main_findchars);
free(main_findchars);
free(findchars);
return 0;
}
char *find_char(char const *source, char const *chars)
{
int count = 0;
int i = 0;
int j = 0;
int charlen = strlen(chars);
int sourcelen = strlen(source);
int findc_yes_no[charlen]; //数组每一位对应给定字符集中的相应的字符
//暂且称为开关数组,1和0代表有和没有
if ((findchars = (char *)malloc(sizeof(chars))) == NULL)
{
printf("malloc error!\n");
exit(1);
}
for(i = 0; i < charlen; i++)
{
findc_yes_no[i] = 0;
*(findchars + i) = '\0';
}
for (i = 0; i < sourcelen; i++)
{
for(j = 0; j < charlen; j++)
{
if(*(source + i) == *(chars + j))
{
/*打印找到的字符在字符串中所处的位置*/
printf("find char '%c' from the %dth of the strings\n", *(chars + j), i + 1);
findc_yes_no[j] = 1;
}
}
}
for (i = 0; i < charlen; i++) //检查开关数组相应字符位
{
if (1 == findc_yes_no[i]) //字符位若为1,把该字符放到findchars中去
{
*(findchars++) = *(chars + i);
count++;
}
}
return (findchars - count);
}
我是在函数中为返回指针开辟了动态存储空间,为了能在最后释放它,我把指针定义在函数外面,这样我就能在主函数中释放它,请问这种方法可行吗?有没有更好的方法,如果有请不吝赐教,非常感谢!








main_findchars = (char *)malloc(sizeof(MAX))// 这样写没意义啊
