Soviet_Mario <Sovie...@CCCP.MIR> writes:
> Il 13/09/19 20:29, Keith Thompson ha scritto:
[...]
>> Local data in a library function is allocated on
>> the calling process's stack.
>
> here I have a doubt instead. As we were talking about malloc
> and dynamic memory, why the "stack" ? The stack is that area
> accessed by bp register for parameters and return values
> (and auto variables), isnt' it ? Many years ago I used to
> read about the "heap" for async. allocated memory, like the
> one got by malloc ...
That was an example. If you call a library function, any local
variables in that function are allocated on the stack associated with
the calling process.
The heap, the region of memory managed by malloc and free or by new and
delete, is handled the same way. It's all associated with the process,
and a new process is created every time you run your program.
(The standard doesn't necessarily refer to "stack" or "heap", but this
is typical for most operating systems.)
As far as memory allocation is concerned (not including space for
executable code), any library functions act just like functions in your
program. If you use static libraries, they're incorporated directly
into your program, as if you had defined them yourself. Dynamic
libraries by design work the same way, except that space for the code is
allocated only once.
>> Again, this is more about the OS than about anything specified
>
> yes, that's why I put [Nix] in the intro of the question. I
> was sure it had necessarily to do with the memory manager of
> the OS. In the end a memory leak in the process should
> bubble up until it.
Ah, I wasn't sure what "[Nix]" meant.
> But, to sum up : a process should not be able, willy nilly,
> if using plain malloc and no particular privilege or other
> tecniques (i.g. to become a daemon and remain loaded), to
> produce a memory leak.
A process can leak memory internally, keeping it allocated (and not
allowing other processes to use it) as long as the process is running.
while (true) {
malloc(1000); // don't do this
}
Operating systems typically place some configurable limit on how much
memory a process can allocate -- but you can bypass that by running
multiple processes. One unprivileged user typically *can* bog down a
system, if not crash it.
But when a process terminates, either because it finishes, or it
crashes, or something kills it, all allocated memory (stack and heap)
is released. That's the operating system's job.