I have read that the following results in undefined behavior.
strcmp(foo, NULL);
But what exactly happens "underneath the hood," so to speak? Is foo
compared to garbage data? Is NULL
dereferenced? What are the details that cause "undefined behavior"?
You pass two pointers, and strcmp dereferences their contents and compares until it meets the difference or null character. Fail happens at different abstraction level, strcmp is fail-free on it's own.
The strcmp() built-in function compares the string pointed to by string1 to the string pointed to by string2 The string arguments to the function must contain a NULL character ( \0 ) marking the end of the string.
The strncmp() built-in function compares at most the first count characters of the string pointed to by string1 to the string pointed to by string2. The string arguments to the function should contain a NULL character ( \0 ) marking the end of the string.
Because a null pointer does not point to a meaningful object, an attempt to dereference (i.e., access the data stored at that memory location) a null pointer usually (but not always) causes a run-time error or immediate program crash.
It depends on the implementation, which is free to assume your parameters are valid (i.e. not null in this case). The behaviour may or may not be reproducible from execution to execution, or from one implementation/platform to another.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With