will the memory allocated by malloc get released when program exits?

K

keredil

Hi,

Will the memory allocated by malloc get released when program exits?

I guess it will since when the program exits, the OS will free all the
memory (global, stack, heap) used by this process.

Is it correct?
 
M

MJ

Hi
Yes it is correct when the program ends all the memory will get
released...
Mayur
 
W

Walter Roberson

MJ said:
Yes it is correct when the program ends all the memory will get
released...

It would be better to quote context.


Neither the C standard nor the POSIX standard explicitly define
exit() [or POSIX _exit()] as freeing memory. Nor does the C standard
define abort() as freeing memory.


In practice, I cannot think of any multi-process operating system
that does -not- free malloc()'d memory when the process ends.
I dunno -- MVS maybe? ;-)

I seem to recall (perhaps incorrectly) that it is not certain that
memory will be freed at process end when one is running in an
embedded environment -- if your toaster-control program somehow
exits [e.g., toaster on fire?] then what meta-process is there to
free the memory?


The original poster asked about malloc()'d memory, not about
"all the memory". The phrase you used, "all the memory", could
be construed to include shared memory segments, mmap()'d segments
and other non-malloc()'d forms -- forms that lie outside the C standard
but which exist on numerous systems. Shared memory segments in particular
are not necessarily released when the creating process terminates.
 
R

REH

MJ said:
Hi
Yes it is correct when the program ends all the memory will get
released...
Mayur

That's not necessarily true. Some versions of Windows do, others do not.
Unix does (At least the ones that I have used do). VxWorks does not.

REH
 
S

Sensei

Will the memory allocated by malloc get released when program exits?

I guess it will since when the program exits, the OS will free all the
memory (global, stack, heap) used by this process.

Is it correct?

It's platform-dependent. Not every OS does it.
 
M

Malcolm

Will the memory allocated by malloc get released when program exits?

I guess it will since when the program exits, the OS will free all the
memory (global, stack, heap) used by this process.

Is it correct?
A decent operating system will do this. If the OS doesn't, the user deserves
to have to reboot, for buying such a trashy system.

You should free all memory in normal operation, to make it easier to detect
leaks. However if the program encounters an error, don't hesitate to just
exit(EXIT_FAILURE) if program logic makes this the natural thing to do.
 
C

Christian Bau

Hi,

Will the memory allocated by malloc get released when program exits?

I guess it will since when the program exits, the OS will free all the
memory (global, stack, heap) used by this process.

Someone will probably give you some answer, but the other question is:
Should you rely on malloc'ed memory being released when the program
exits?

First of all, you can't just keep on allocating memory. Your program
will either run out of memory at some point, or it will get slower and
slower if you allocate more and more memory and don't call free () when
it is not used anymore.

But you should also consider that what is one program today, might be a
tiny component of a program next year. So if you relied an the operating
system releasing memory when the program exits, you now have a function
that doesn't release its memory. And if you call it repeatedly, you run
into trouble.

It is best to always match allocation and deallocation of memory.
 
M

Mark F. Haigh

Malcolm said:
A decent operating system will do this. If the OS doesn't, the user deserves
to have to reboot, for buying such a trashy system.

Many RTOSs do not free memory on program exit. For these systems, it's
a design tradeoff, not a quality issue.
You should free all memory in normal operation, to make it easier to detect
leaks. However if the program encounters an error, don't hesitate to just
exit(EXIT_FAILURE) if program logic makes this the natural thing to do.

Please don't. Always free all memory you allocate.


Mark F. Haigh
(e-mail address removed)
 
M

Malcolm

Mark F. Haigh said:
Please don't. Always free all memory you allocate.
Unfortunately this advice, though well-meaning, is impractical. Errors occur
mid processing, often leaving structures in a corrupted or half-build state.
So freeing everything can be complicated. Then it is even more difficult to
test the freeing code, and it might itself generate errors.

So unless freeing all memory in all circumstances is an absolute
requirement, which is unusual, it is much better to simply exit with an
error message if it becomes necessary to abort.
 
R

Russell Shaw

Malcolm said:
Unfortunately this advice, though well-meaning, is impractical. Errors occur
mid processing, often leaving structures in a corrupted or half-build state.
So freeing everything can be complicated. Then it is even more difficult to
test the freeing code, and it might itself generate errors.

So unless freeing all memory in all circumstances is an absolute
requirement, which is unusual, it is much better to simply exit with an
error message if it becomes necessary to abort.

You only need to free at program termination in systems with no hardware
memory manager.
 
W

Walter Roberson

You only need to free at program termination in systems with no hardware
memory manager.

That is not accurate.

The presence or absence of a hardware memory manager has nothing
to do with whether there is some kind of executive kernel
which is keeping track of memory allocation.

I have programmed on systems that had hardware memory management
but which did not use it for tracking memory allocatiion,
and I have programmed on systems that had no hardware memory
management but which -did- track memory allocation in the kernel.

In Unix, memory allocation is based on the brk() and
sbrk() *system calls* -- and the operating system can use
any mechanism it wishes for tracking memory allocation.
 
K

keredil

Of course I will free the memory in my code. It's just an interview
question.

So the answer is that it will depend on the OS, right? Some systems
will free the memory allocated by malloc when program exits, while
others not.

Correct?
 
L

Lawrence Kirby

Many RTOSs do not free memory on program exit.

Really? I can understand this for low level embedded systems, where
termination of the program is a pretty much terminal fault anyway. But
memory reclamation doesn't generate obvious issues for a real-time system,
it can be given a low priority. A RTOS that doesn't reclaim memory
properly risks running out of resources i.e. not being able to guarantee
what a program needs to run. That strikes me as a rather significant flaw
in a RTOS.
For these systems, it's
a design tradeoff, not a quality issue.

For a RTOS it is a fundamental quality issue.
 
L

Lawrence Kirby

It's platform-dependent. Not every OS does it.

But if you choose to limit yourself to OSs that do you won't be limiting
yourself very much in practice. How many OSs can you name that don't do it?

As far as C is concerned you get no more guarantees about the releasing of
freed memory, automatic variable etc. than you do about unfreed memory.

Lawrence
 
L

Lawrence Kirby

That's not necessarily true. Some versions of Windows do, others do not.

What versions of Windows don't? Even DOS implementations managed to get
this right. Win16 certainly had the mechanisms to do this properly (IIRC
it was called LocalAlloc).

Lawrence
 
S

Sensei

Lawrence said:
But if you choose to limit yourself to OSs that do you won't be limiting
yourself very much in practice. How many OSs can you name that don't do it?

As far as C is concerned you get no more guarantees about the releasing of
freed memory, automatic variable etc. than you do about unfreed memory.

Not only that. Ok, many OS have garbage collectors for processes that
ended, in one way or another, but don't rely on that. Moreover,
allocating memory just for fun and not deallocating it makes your
program huge and slower for no reason, so deallocate the memory you
don't use anymore.

malloc() and free() are siblings, use them always and with care :)
 
C

CBFalconer

Of course I will free the memory in my code. It's just an interview
question.

Not necessarily. Especially if you are using a malloc/free package
that has O(N*N) performance when there are many items to free.
This is quite common - the thing that is not so common is programs
that end with large numbers of items allocated and then free them
all.

You can demonstrate the phenomenom easily with the test program for
my hashlib system, which has provision for avoiding the final
frees. I forget the number where the effect became obvious, it
might have been 200,000 or maybe 2,000,000 items. It shows up as a
huge delay between telling the program to exit and getting a prompt
back. I found the O(N*N) effect on DJGPP, LCC_WIN32, and VC6.

The effect caused me to track down the culprit, and develop the
nmalloc package for DJGPP. nmalloc is O(1) for a single free, and
thus O(N) for a large count of items to free. Hashlib is portable,
nmalloc is not (and cannot be). You can see (and get) the packages
at:

<http://cbfalconer.home.att.net/download/>

For those interested, the free delays have to do with stitching
together freed memory with other free blocks. The troublesome
systems have to search all blocks for possible adjacencies, which
is an O(N) operation, thus making free and O(N) operation, and
freeing of all N blocks an O(N*N) operation. nmalloc keeps track
of physically adjacent blocks so that the adjacency search consists
of examining two pointers, and is thus O(1).
 
W

Walter Roberson

Moreover,
allocating memory just for fun and not deallocating it makes your
program huge and slower for no reason,

In most modern Unix OS, allocating large amounts of memory is usually
sub-linear time in the number of "pages" of memory to be allocated --
just long enough to allocate the memory virtually from zero-initialized
automatic store. The task of finding a physical page to go along with
the virtual memory is often deferred until the first write to the page.

Thus, as usual, any time one is talking about what is "slower" or not,
one should write qualifications or conditionally. Yes, there are
operating systems and hardware in which allocating large amounts
of memory makes your program slow, but there are others in which it
barely makes a difference.

On some systems, it is far more important as to how the memory is
allocated then the total storage used. For example, 100,000 malloc() of
8 bytes each is often noticably slower than 8 allocations of 1,000,000
each.
 
M

Mark F. Haigh

Walter said:
Ah? Even if you caught a SIGSEGV?


Let's examine for a moment how one can come across a SIGSEGV:

1. Through undefined behavior leading to "an invalid access
to storage" (C99 7.14#3), although such conditions are not
required to be detected (C99 7.14#4).

2. As a result of calling raise (or other POSIX or system-
specific functions, e.g. kill).

If your program goes the way of #1, then internal C library memory
allocation structures may be corrupted or inconsistent. This is often
seen when overflowing a malloc-ed buffer or freeing a non-allocated or
invalid buffer location (including double frees). It should be obvious
why one should not allocate or free memory within a SIGSEGV handler.

The C standard is clear enough regarding what is allowed from a SIGSEGV
handler:

7.14 [...]
[#5] If the signal occurs other than as the result of
calling the abort or raise function, the behavior is
undefined if the signal handler refers to any object with
static storage duration other than by assigning a value to
an object declared as volatile sig_atomic_t, or the signal
handler calls any function in the standard library other
than the abort function or the signal function with the
first argument equal to the signal number corresponding to
the signal that caused the invocation of the handler.
[...]

But it's the undefined behavior that's the underlying problem. Some
implementations may be able to report certain undefined behavior via
SIGSEGV, and some may not. The best way to avoid having to worry about
it is to write correct, robust programs that do not invoke undefined
behavior.

Users of POSIX-compliant systems may be able to differentiate #1 from
#2 via the si_code member of siginfo_t.


Mark F. Haigh
(e-mail address removed)
 

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

No members online now.

Forum statistics

Threads
473,767
Messages
2,569,570
Members
45,045
Latest member
DRCM

Latest Threads

Top