返回信息流看书有这样一段程序:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct TAG_datastruct{
char* string;
}datastruct;
datastruct* getinput(void);
void printmessage(datastruct* todisp);
int main(void)
{
int counter;
int maxval=0;
datastruct* svalues[200];
for(counter=0;counter<=200;counter++)
{
svalues[counter]=getinput();
if(!svalues[counter]) break;
maxval=counter;
}
printmessage(svalues[maxval/2]);
return 0;
}
datastruct* getinput(void)
{
char input[80];
datastruct* instruct;
printf("enter a string,or leave blank when done:");
fgets(input,79,stdin);
input[strlen(input)-1]=0;
if(strlen(input)==0)
return NULL;
instruct=malloc(sizeof(datastruct));
instruct->string=strdup(input);
return instruct;
}
void printmessage(datastruct* todisp)
{
printf("the middle string is:\n");
printf("%s\n",todisp->string);
}
调用malloc不需要free释放吗?而且strdup也调用了malloc
自己在后面加了free( instruct->string)输出变成乱码
新手请教,多谢各位指点
这是一条镜像帖。来源:北邮人论坛 / cpp / #19440同步于 2009/2/23
该镜像源已超过 30 天没有更新,可能在源站已被删除。
CPP机器人发帖
关于malloc和free
pineapple
2009/2/23镜像同步4 回复
订阅后,新回复会通过你的通知中心匿名送达。
4 条回复
指针用完了再free
【 在 pineapple (pineapple) 的大作中提到: 】
: 看书有这样一段程序:
: #include <stdio.h>
: #include <stdlib.h>
: ...................
好的编程习惯确实应该是malloc以后必须要free的。
光拿这种简单的程序来说倒是无所谓,反正main函数执行完毕以后,内存都收回的。
较好的方式是,在哪一层调用上malloc就在哪一层free掉。
因此尽量不要像这个例子一样写。
可以在子函数外面malloc,并通过参数传到子函数内部进行操作,最后还是回到调用者这里free掉。
如下:
char * p = (char*)malloc(...);
a_function(p);
free(p);