[OT] Can global variable be passed into Python function?

Chris Angelico rosuav at gmail.com
Sun Mar 2 14:32:28 EST 2014


On Mon, Mar 3, 2014 at 6:17 AM, Dave Angel <davea at davea.name> wrote:
> Array size is inside the malloc block, but outside the struct
>  block.  As you can see if you try to delete without the brackets
>  when you used new [], some runtimes will crash.

As in, you have to use "delete [] x" to correspond with "x = new
whatever[n]"? Yes, that's right, but that array size is earlier in
memory than x itself. I can pretend that x is the same as one declared
statically as "whatever x[n]", and it'll function the same way. When
new[] is implemented using malloc(), it'll be something like this:

{
    data = malloc(n * sizeof(whatever) + sizeof n);
    *(int *)data = n;
    return ((int *)data)+1;
}

so in that case, the array size is inside the malloc'd block, but it's
still invisible to the calling function. A fully compliant C++
implementation could choose to store that elsewhere, in some kind of
lookup table - it could then easily catch bugs like "delete
malloc(1)", "delete [] malloc(1)", "delete [] new whatever", and
"delete new whatever[1]" (because the pointer given wouldn't be in the
'new' table or the 'new[]' table, respectively).

ChrisA



More information about the Python-list mailing list