I am trying to subscribe to an event sent from a Xenon with the feathering ethernet adapter to a Photon. I am initially able to read the first event sent from the Xenon but after I am not able to get anything different. Here is the code:
}
}
Although I am sending other events with different data the LED I am controlling never turns off. I have tried including an else if statement as well and a return in the if statement and the rest outside of a condition but have had no luck.
Any help or insight into the subscribe feature that may be causing this issue would be much appreciated.
Thanks so much!
While it is a good advice to (almost) always opt for the n version of string functions, in case of strncmp() the rational for limiting the scope isn’t really to protect against overrun since there is little harm in a read-overrun and in the given example strcmp(data, "open") will do exactly the same thing as strncmp(data, "open", 4).
Both versions only read data from memory, so no danger of memory corruption, and both will terminate as soon a difference or zero-terminator is found.
Since the literal "open" is 100% certain to be null-terminated the comparison will end there (the latest).
However, there are two cases (I can think of) where strncmp() would be required
if both sides of the comparison are not certain to be zero-terminated to prevent the function from traversing the whole address space to find a difference (which will probably be found rather sooner than later, but nevertheless performance would be degraded)
the more likely case, when you only want to check for a known-length prefix in two strings that will probably be longer than that length.
However with both versions you can get a false positive when you compare something like this …
… since both will end prematurely due to the terminating zero in s[].
In order to overcome that one could use memcmp(p1, p2, n) which will always check no less and no more than n bytes.
@ScruffR - thanks for correcting/clarifying the explanation I gave in a hurry and explaining why it is more prudent to use strncmp() rather than strcmp() even though it is not 100% in all cases.