Re: Someone stomping on our memory

From: Alex Rousskov <rousskov@dont-contact.us>
Date: Fri, 10 Nov 2000 17:23:08 -0700 (MST)

On Sat, 11 Nov 2000, Andres Kroonmaa wrote:

> please explain me some C stuff:
>
> /* allocate a variable size buffer using best-fit pool */
> memAllocBuf(size_t net_size, size_t * gross_size)
> {
> [...]
> *gross_size = pool ? pool->obj_size : net_size;
> ...
> stringInitBuf(String * s, size_t sz)
> {
> s->buf = memAllocBuf(sz, &sz);
> assert(sz < 65536);
> s->size = sz;
> }
>
> stringLimitInit(String * s, const char *str, int len)
> {
> assert(s && str);
> stringInitBuf(s, len + 1);
> s->len = len;
> xmemcpy(s->buf, str, len);
> s->buf[len] = '\0';
> }
>
> So, memAllocBuf is modifying sz which is passed by pointer.
> memAllocBuf is called from stringInitBuf which gets sz from stack.
> stringInitBuf is called from stringLimitInit which passes len+1 for sz.

Right. So, effectively, memAllocBuf is modifying sz. Sz is local to
stringInitBuf. It does not matter that it is a function parameter.
Most automatic local variables are allocated "on stack".
 
> I don't get how this should work.
> memAllocBuf is modifying something that is on the stack, and is
> produced runtime on the fly.

Sz is visible and used inside stringInitBuf only. Sz's value is copied
to s->size. It does not matter how sz got its initial value (which
happened to be len+1).

> Is it allowable to modify proc() params passed on stack? Is this reliable?
> What if &sz won't get modified?

Function parameters are equivalent to local variables. All of the
operators below are "legal" and reliable.

        void f(int a1) {
                int a2 = a1;
                int *pa = &a1;
                a2 = *pa;
                *pa = a1;
        }

The fact that a parameter can get modified was one of the reasons C++
got "references" (references cannot be modified and, hence, are
important clues for compiler optimizations). In C, you could say
something like:

        void f(const int a1);

if you want to help a compiler, but it may not be very portable and
gets messy with pointers:

        void f(const int * const a1);

Alex.
Received on Fri Nov 10 2000 - 17:23:13 MST

This archive was generated by hypermail pre-2.1.9 : Tue Dec 09 2003 - 16:12:57 MST