English 中文(简体)
从C类职能中解放记忆
原标题:
  • 时间:2009-05-26 16:14:20
  •  标签:

在C,从职能中解放记忆的最好做法是:

  • Provide a "destructor" function that encapsulates the call to free().
  • Require users to free() the returned pointer themselves.

例如,我们开设并关闭档案:

FILE* f = fopen("blah", "w");
fclose(f);

最好是:

FILE* f = fopen("blah", "w");
fclose(f);
free(f);

<>strong>Warning: 免费拨打国际能源论坛协调人。 我只在这里使用一种假设性的实施。

当地变数与回来记忆有何关联? 这里是否是免费的? (或也许永远不应这样做)

FILE f = &fopen("blah", "w");
fclose(&f);
最佳回答

<> >>,<>>,>,>,>,>,>,>,>,<>,>,>,>,>。

:

页: 1

(1) __________________________ FILE*free/code above...

2),<>,> ∗∗∗∗∗ <<>>>>> >>

∗∗∗ __________________

问题回答

< > >> > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > ......

页: 1

int * mymem = (int *)malloc(20 * sizeof(int));
...
a_func_to_call(mymem);
...
free(mymem);

• :

FILE* f = fopen("blah", "w"); // allocs a FILE struct
fclose(f); // The implementation of fclose() will do what s necessary to 
           // free resources and if it chooses to deallocate any memory
           // previously allocated

You can t free FILE* it wasn t allocated by malloc.
Since you weren t responsible for allocating it - you shouldn t free it.

。 用于确定所有进一步行动上游的目标:档案。 页: 1

>

About your question on providing destructor kind of function to free the memory: I feel it is appropriate to provide a destructor kind of function if the function does more than freeing the memory.

wrapperFree(Pointer* p)
{
 //do some additional work [ other cleanup operations ]
 free(p);
}

页: 1

<>>>> > >

。 页: 1

∗∗ UNEP/POPS/POPRC.2/1。

  • Make a "destructor" function when something needs to happen apart from freeing the memory. The FILE * stuff is a fine example: it must deal with the file itself as well as dealing with the memory.
  • Use bare free() when it s just a chunk of memory. Anything else is overkill.

缺乏最佳做法......

但是,我这样说,信息传递原则意味着,职能中使用的记忆分配和分配细节一般应在职能范围内加以概括。

公开/公开职能应归还某种不公开的操作,这种操作是关闭的/由密切职能分配的。

可认为FLE* 是一种不透明的做法。

如前所述,在相应的职能(即建筑商/司机)内总结你的“保存”守则,一般是良好做法,特别是在处理例外处理时,或者甚至在指定你自己的出任/发货人时,这种做法也可能有用:

在此情况下,拥有一位脱轨助手非常有用,因为你可以简单地将其登记为具有诸如(exit)等职能,以便它们自动地要求终止方案,从而可以适当地清理全球国家。

我不仅像爱护者的职能一样,而且像Dave Hanson的《公约》一样,《公约》通过点人address,而且《公约》规定,点人可以免费:

Thing_T *Thing_new(void);
void Thing_dispose(Thing_T **p);   // free *p and set *p = NULL




相关问题
热门标签