mity / md4c

C Markdown parser. Fast. SAX-like interface. Compliant to CommonMark specification.
MIT License
756 stars 138 forks source link

Suspicious IS_INPUT_STR check #109

Closed dangelog closed 4 years ago

dangelog commented 4 years ago

Hi,

md4c.c has this macro currently defined:

#define IS_INPUT_STR(ptr)       (ctx->text <= (ptr)  &&  (ptr) < (ctx->text + ctx->size))

It seems to be used to know if a given pointer is pointing within a chunk of text (so it doesn't have to be freed -- it's a "view" into a buffer of text owned by someone else), or if it's owning the pointee and thus it needs to be free()d manually.

If it is the case, the check is illegal. One cannot compare pointers into different "objects"; that triggers undefined behavior. Cf N2176 (C18's draft) §6.5.8.5 Relational operators

When two pointers are compared, the result depends on the relative locations in the address space of the objects pointed to. If two pointers to object types both point to the same object, or both point one past the last element of the same array object, they compare equal. If the objects pointed to are members of the same aggregate object, pointers to structure members declared later compare greater than pointers to members declared earlier in the structure, and pointers to array elements with larger subscript values compare greater than pointers to elements of the same array with lower subscript values. All pointers to members of the same union object compare equal. If the expression P points to an element of an array object and the expression Q points to the last element of the same array object, the pointer expression Q+1 compares greater than P . In all other cases, the behavior is undefined.

(emph. mine, and I think we're in that case).

Thanks for reading,

mity commented 4 years ago

Thanks. Looking at it.