Lewis Liu
Lewis Liu

Reputation: 67

malloc pointer cause memory leak?

I have following code, will this cause memory leak, after function returns, there are many mallocated memory, not claimed?

#include <stdlib.h>

struct test
{
    char * name;
    char * value;
};

void test_ok()
{
   int i;
   struct test * ok;

   for (i=0;i<10000;i++)
   {
       ok =malloc(sizeof(struct test));
   } 

}
void main ()
{
    int j=0;
    while(j<60)  
    {
      test_ok();
      j++;
      sleep(1);
    }

}

Upvotes: 0

Views: 701

Answers (4)

Sourav Ghosh
Sourav Ghosh

Reputation: 134276

In your code, test_ok() is never called, so the malloc() is never executed. So no memory allocation happens, no question of memory leak there.

Any decent compiler will optimize away the test_ok() code, anyway.


EDIT:

If you actually make a call to test_ok() from the main(), it will eventually call the function, allocate the memory via calling malloc() [provided malloc is success] and do nothing. So, theoretically, yes, you'll have memory leaks there, plenty.

Point to note: As you mentioned,

[...] after function returns [...]

assuming you're talking about test_ok() function, no, simply returning from a function with a malloc-ed pointer does not cause memory leak. A leak happens when you miss to release the memory after the usage is done (no referenced/used anymore).

When exiting the program, returning from main(), all the allocated memories will be de-allocated anyways. The problem due to memory leak appears when a program keeps on running.

That said, as per the latest standards, void main() is not a valid signature for hosted environments, you should use int main(void), at least.

Upvotes: 3

DarioP
DarioP

Reputation: 5455

Before reassigning the pointer, you should free it. Otherwise the previously allocated memory is no longer pointed by anything (but still allocated), therefore leaked.

Upvotes: 1

Mureinik
Mureinik

Reputation: 310983

You program doesn't call test_ok(), so the answer is no.

Had test_ok() be called, the answer would have been yes. You are allocating memory on the heap using malloc and not cleaning it up afterwards with free.

EDIT: Now the OP has been edited to call test_ok(), so yes, this program would leak memory.

Upvotes: 2

ljedrz
ljedrz

Reputation: 22163

Not unless you actually call test_ok() from within main().

Upvotes: 1

Related Questions