:: Re: [DNG] "Common knowledge?"-quest…
Page principale
Supprimer ce message
Répondre à ce message
Auteur: Rainer Weikusat
Date:  
À: dng
Sujet: Re: [DNG] "Common knowledge?"-question
Peter Olson <peabo@???> writes:

>> On January 23, 2016 at 1:36 PM Rainer Weikusat
>> <rainerweikusat@???> wrote:
>>
>> Peter Olson <peabo@???> writes:
>> 5>> On January 22, 2016 at 4:34 PM Rainer Weikusat
>> <rainerweikusat@???> wrote:
>>
>> [...]
>>
>> >>     p = buf = alloca(total);

>>
>> [...]
>>
>> > the failure mode of alloca is SIGSEGV or some other malfunction and
>> > there is no way to test for it
>>
>> It's supposed to allocate memory in the current stack frame which will
>> work unless the stack has already grown to the limit.
>
>>From man7.org/linux/man-pages/man3/alloca.3.html section BUGS:
>        There is no error indication if the stack frame cannot be extended.
>        (However, after a failed allocation, the program is likely to receive
>        a SIGSEGV signal if it attempts to access the unallocated
>        space.)


Calling this a bug is technical nonsense: The way stack allocation works
for a single-threaded process on UNIX(*) etc is that the code just uses
whatever it needs and that the kernel's supposed to handle faults
resulting from accessing a not-yet-valid address by making it available.
In this respect, there's no difference between alloca and static stack
allocations. If a program tries to use more stack space than can be
provided, it may end up getting a SIGSEGV. Or it may silently overwrite
memory used for something different. In either case, the code cannot
possibly work in the it was written.

OTOH, space allocated on the stack will be automatically reclaimed after
the corresponding function returned which is the best 'automatic memory
management' one can get in C. It's also good for locality as different
functions called at the same depth will keep using the same memory area.

> I have never been a fan of alloca though it obviously _can_ be used safely with
> a little care.


Do you realize that Linux uses 8K kernel stacks (and can be configured
to use 4K) with no protection against overwriting whatsoever? In
contrast to this, even on the 32 bit system, the userspace stack area is
practically infinite compared to the memory requirements of small
program and this becomes even more true on 64bit systems.

With some amount criminal energy, it's possible to use the stack
'unsafely'.