c - C99: Will arrays or heap-allocated buffers ever end at UINTPTR_MAX? -



c - C99: Will arrays or heap-allocated buffers ever end at UINTPTR_MAX? -

can assume next invariant?

void foo(char *buf, size_t len) { // "buf" points either array or memory allocated malloc(). assert((uintptr_t)(buf + len) < uintptr_max); }

in parser writing want mark offsets using pointers: illustration might have char *end_of_submessage, end_of_submessage relative current buffer. if submessage not end within current buffer, want utilize value larger offset in current buffer perchance be. do:

void parse(char *buf, size_t len, uintptr_t end_of_submessage) { // parsing might increment "buf" // ... // if end_of_submessage == uintptr_max, processing not // triggered if have processed our entire current buffer. if ((uintptr_t)buf >= end_of_submessage) process_submsg_end(); }

but scheme thwarted if malloc() returned memory such ptr + len == uintptr_max, or array had same property. safe assume never happen? safe according standard? if not, safe in practice?

the guarantee c standard provides follows:

iso/iec 9899:1999(e) §7.18.1.4/1

the next type designates signed integer type property valid pointer void can converted type, converted pointer void, , result compare equal original pointer:

intptr_t

the next type designates unsigned integer type property valid pointer void can converted type, converted pointer void, , result compare equal original pointer:

uintptr_t

these types optional.

no guarantees given precise content of these converted integers. in particular, given char pointer p, (uintptr_t)(p + 1) == ((uintptr_t)p) + 1 not guaranteed true.

if want mark offsets, should utilize ptrdiff_t offset pointer, or can utilize pointer mark end. example:

void parse(char *buf, size_t len, char *end_of_submessage) { // ... if (buf >= end_of_submessage) process_submsg_end(); }

if end_of_submessage may lie in different buffer, can utilize like:

char *buf_start = buf; // ... if (buf_start <= end_of_submessage && buf >= end_of_submessage) process_submsg_end();

c pointers c99 intptr

Comments

Popular posts from this blog

iphone - Dismissing a UIAlertView -

intellij idea - Update external libraries with intelij and java -

javascript - send data from a new window to previous window in php -