crash in strcmp(f(), g()) if g() returns NULL.

Apr 6, 2012 at 11:41am
I see that strcmp does not crash when NULL is passed as an argument.
But the same stuff , if the same NULL argument is being passed from the return value of a function.
Please see the below code snippet.

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
class myString {
public:
myString(char *);
char * value;
char * getString();
bool compare(myString *);
};

myString::myString(char *temp) {
value = temp;
}
char *
myString::getString() {
return value;
}

bool
myString::compare(myString * temp) {
if (strcmp(getString(),temp->getString()) == 0) {
printf("true \n");
return true;
}
printf("false \n");
return false;
}

main() {
const char * a = NULL;
const char * b = "ashishk";
strcmp(b,a);
strcmp(a,b);
strcmp(b,b);
strcmp(a,a);
char * w = (char *)malloc(10);
char * x = (char *)malloc(10);
char * y = (char *)malloc(10);
char * z = NULL;
strcpy(w, "ashish");
strcpy(x, "kumar");
strcpy(y, "ashish");
myString A(w);
myString B(x);
myString C(y);
myString D(z);
A.compare(&B);
A.compare(&C);
A.compare(&D); /* it crashes inside here in strcmp */
}
Apr 6, 2012 at 11:51am
I don't think strcmp is designed to handle null pointers. Just don't pass null pointers to it and it should work fine.
Apr 6, 2012 at 11:55am
Firstly when posting code remember to put it in code blocks. It may be because you are calling temp->getString() when temp is null.
Last edited on Apr 6, 2012 at 11:56am
Apr 6, 2012 at 1:06pm
Hi Easton,
Sorry for not using code blocks. Here temp is not null. temp is a valid object.

Peter87,
Is the strcmp's behavior undefined for NULL parameter? Further In my actual code strcmp has been used at thousands of places. I can put a NULL check at each of the strcmp call. It will be better to resolve the crash. But it would also have a performance impact.
OR
is it the fact that we should put null check when strcmp's arguments are actually function calls. There we would put a check and in cases where the address is directly passed to strcmp, then we do not need a check.
i.e. strcmp(ptr1,ptr2) is fine.
but strcmp(f(),g()) should be
if (f() && g()) {
strcmp(f(),g())
}

Apr 6, 2012 at 2:18pm
I think it's undefined and it doesn't matter if the pointer comes from a function call or not.

You should consider using std::string so you don't have to care about these low level details.
Topic archived. No new replies allowed.