Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this a correct and portable way of checking if 2 c-strings overlap in memory?

Tags:

c

Might not be the most efficient way, but is it correct and portable?

int are_overlapping(const char *a, const char *b) {   return (a + strlen(a) == b + strlen(b)); } 

To clarify: what I'm looking for is overlap in memory, not in the actual content. For example:

const char a[] = "string"; const char b[] = "another string"; are_overlapping(a, b); // should return 0 are_overlapping(a, a + 3); // should return 1 
like image 973
infokiller Avatar asked Jul 09 '13 23:07

infokiller


People also ask

What is memory overlapping in C?

If the memory segments coincide at some point, a "overlapping" would occur. Imagine a memory segment starts at address 0x51, and the other starts at address 0x70, and you try to copy 50 bytes from 0x51 to 0x70... at some point, the process will start reading from address at 0x70, and copying to address 0x8F.

What is overlap in memmove?

It's very simple. Consider memmove(dest, source, length) . If the range of bytes specified by the range source to source + length - 1 include any bytes in the range specified by dest to dest + length - 1 , the two ranges overlap. This is most likely to happen when moving elements within an array.


1 Answers

Yes, your code is correct. If two strings end at the sample place they by definition overlapped - they share the same null terminator. Either both strings are identical, or one is a substring of the other.

Everything about your program is perfectly well-defined behaviour, so assuming standards-compliant compilers, it should be perfectly portable.

The relevant bit in the standard is from 6.5.9 Equality operators (emphasis mine):

Two pointers compare equal if and only if both are null pointers, both are pointers to the same object (including a pointer to an object and a subobject at its beginning) or function, both are pointers to one past the last element of the same array object, or one is a pointer to one past the end of one array object and the other is a pointer to the start of a different array object that happens to immediately follow the first array object in the address space.

like image 168
Carl Norum Avatar answered Sep 16 '22 14:09

Carl Norum