开发者

memory leak in c

will the following code res开发者_运维百科ult in memory leak

char * a()
{
   char * b = malloc(100);
   return b;
 }

B()
{ 
  char * c = a();
  free (c);
}


No. You're freeing the allocated memory after all. The general rule is, if you're calling free() for each malloc() function call, then that means you're not leaking memory.


No.

You are allocating memory inside a(), returning a pointer to that memory, which you're freeing in B().


In the function B(), it will definitely NOT cause a memory leak because you are calling free. But It WILL cause a memory leak if you call a() without calling free, so in case you are getting some memory leaks and wondering why it is happening, then look somewhere else where you are calling the function a() without calling free() after that.


No. You allocate the memory, then free the memory at the same address (even if the pointer that contains that address has been copied around).


It will not leak memory. Your function a() is returning the address of memory location to function b() which is being freed. Do not get confused with allocation and de-allcation of memory in different functions. It will work fine since memory you are allocating is on heap which is common area for both functions e.i. a() & b() (as far as they are in same address space).


I don't think so... Why do you think it could result in a leak? The memory you allocate is the same that you free.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜