top | item 44048982

(no title)

sqrt_1 | 9 months ago

Related to unspecified vs undefined. I recall some C code was trying to be tricky and read from just allocated memory. Something like:

int* ptr = malloc(size); if(ptr[offset] == 0) { }

The code was assuming that the value in an allocated buffer did not change.

However, it was pointed out in review that it could change with these steps:

1) The malloc allocates from a new memory page. This page is often not mapped to a physical page until written to.

2) The reads just return the default (often 0 value) as the page is not mapped.

3) Another allocation is made that is written to the same page. This maps the page to physical memory which then changes the value of the original allocation.

discuss

order

Arnavion|9 months ago

A read from an unmapped page producing a different value than reading from that same page after it's mapped is an OS bug (*). If this was an already allocated page that had something written to it, reading from it would page it back in and then produce the actual content. If this was a new page and the OS contract was to provide zeroed pages, both the read before it was mapped and the read after it was mapped would produce zero.

What could happen is that the UB in that code could result in it being compiled in a way that makes the comparison non-deterministic.

(*): ... or alternatively, we're not talking about regular userspace program but a higher privilege layer that is doing direct unpaged access, but I assume that's not the case since you're talking about malloc.