sbrk(2) question

Richard Tobin richard at aiai.ed.ac.uk
Thu Mar 14 01:42:43 AEST 1991


In article <6582 at auspex.auspex.com> guy at auspex.auspex.com (Guy Harris) writes:
>Umm, why would it not be zero in that situation?  If the memory has
>truly been released, as in "handed back to the kernel", it should be
>re-zeroed if allocated to a process again.

Yes, of course.

> (I.e., calling "sbrk()" with
>a negative argument, in most if not all versions of UNIX, doesn't just
>set some user-mode pointer so that the memory stays in the address space
>of the process.)

Even if it does this, will it not release memory in page-size units?
A quick check on a Sun, Sequent, BSD Vax and Orion all reveal that the
bytes before the first page boundary in the (re-)allocated space are
unzeroed (and indeed contain the data unchanged from before).

So you can't rely on sbrk() space to be completely zeroed, unless you're
sure nothing has already allocated and freed memory.  And you can't be
sure of that (maybe the system did it before calling main(), for example).

While experimenting, I was reminded of another hazard of sbrk().  For
example, this program produces a segmentation fault on a Sun4 under
SunOS 4.1:

    #include <stdio.h>
    
    extern char *sbrk();
    
    main()
    {
        sbrk(100000);
        printf("hello world\n");
        sbrk(-100000);
        printf("hello again\n");
    
        exit(0);
    }

-- Richard
-- 
Richard Tobin,                       JANET: R.Tobin at uk.ac.ed             
AI Applications Institute,           ARPA:  R.Tobin%uk.ac.ed at nsfnet-relay.ac.uk
Edinburgh University.                UUCP:  ...!ukc!ed.ac.uk!R.Tobin



More information about the Comp.unix.questions mailing list