repeat malloc & memory fragmentation

S

spasmous

Yo,

I'm running a subroutine that mallocs a 10 or so Mb, then frees it on
exit. Then when it's called again it mallocs/frees again, and so on
for maybe 100 calls.

Sometimes the code fails after running a long time - is it possible
that malloc needs a contiguous block of memory but my frequent mallocs
have fragged it all up and so the later mallocs fail. Or... am I just
a bad programmer ;)

Thanks for your input.
 
L

lilburne

spasmous said:
Sometimes the code fails after running a long time - is it possible
that malloc needs a contiguous block of memory but my frequent mallocs
have fragged it all up and so the later mallocs fail.

Yes malloc will require a contigous block of memory.
 
D

David Harmon

Yes malloc will require a contigous block of memory.

But it will more often be found that the program has a memory leak
(forgetting to free something that should be) and is actually running
out of available.
 
L

lilburne

David said:
But it will more often be found that the program has a memory leak
(forgetting to free something that should be) and is actually running
out of available.

Maybe, but then he doesn't say that the program has started
paging prior to running out of memory.
 
D

David Harmon

Maybe, but then he doesn't say that the program has started
paging prior to running out of memory.

Maybe, but he doesn't say much. Is there any more reason to think the
program would resort to paging to satisfy memory requests when the heap
was full than it would when the heap is fragmented?
 
P

Paul

spasmous said:
Yo,

I'm running a subroutine that mallocs a 10 or so Mb, then frees it on
exit. Then when it's called again it mallocs/frees again, and so on
for maybe 100 calls.

Sometimes the code fails after running a long time - is it possible
that malloc needs a contiguous block of memory but my frequent mallocs
have fragged it all up and so the later mallocs fail. Or... am I just
a bad programmer ;)

Thanks for your input.

How about looking at what you're doing between the calls of malloc and
free? Maybe something in there is causing the problem. To convince
yourself, why not write a very simple program that just allocates and
frees 10 Meg of memory in a loop?

#include <cstdlib>

void allocate_stuff()
{
char *p = (char *)malloc( 10000000 );
free(p);
}

int main()
{
char *p;
for ( int i = 0; i < 100; ++i )
allocate_stuff();
}

This code does what you describe. Does it cause problems as you've
described them, or does it run smoothly?

Paul
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,537
Members
45,024
Latest member
ARDU_PROgrammER

Latest Threads

Top