Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In C, what exactly happens when you pass a NULL pointer to strcmp()?

Tags:

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"?

like image 593
jfmercer Avatar asked Feb 18 '14 20:02

jfmercer


People also ask

What happens if you pass null to strcmp?

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.

Does strcmp work with null?

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.

Does strncmp check for null?

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.

What happens if you access a null pointer?

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.


1 Answers

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.

like image 70
justin Avatar answered Oct 20 '22 06:10

justin