Reputation: 165
will the following code result in memory leak
char * a()
{
char * b = malloc(100);
return b;
}
B()
{
char * c = a();
free (c);
}
Upvotes: 1
Views: 292
Reputation: 20189
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.
Upvotes: 2
Reputation: 193
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.
Upvotes: 0
Reputation: 95
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).
Upvotes: 0
Reputation: 385174
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).
Upvotes: 0
Reputation: 229108
No.
You are allocating memory inside a(), returning a pointer to that memory, which you're freeing in B().
Upvotes: 3
Reputation: 361472
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.
Upvotes: 10