tags:

views:

62

answers:

3

I'm currently trying to test a strcat() function that I wrote myself. Instead of printing the outputs and checking them line by line manually, I've decided to use assert from assert.h. The problem is that assert is showing errors even though the outputs look totally fine. The following is my code:

void mystrcat_test()
{
    char str[BUFSIZ];
    assert(strcmp(str, ""));
    mystrcat(str, "hello");
    assert(strcmo(str, "hello"));
}
+2  A: 

In C, if (auto) variables are not explicitly set, they can contain any value, not just zero, even though it is common. An int for instance is often 0 if not set, but can actually be any value. The same goes for all types, including char arrays.

str in this case may contain anything, i.e. it may not be empty. It is not initialized, so your assert for the strcmp with "" can hit you.

Also, as Paul R pointed out, the logic for assert() is inverse to what strcmp() returns. 0 means success for strcmp() but failure to assert().

This can instead be written as:

assert(0 == strcmp(str, "hello"));

or

assert(!strcmp(str, "hello"));

If you want to it to be empty, you can use a static declaration, like so:

static char str[BUFSIZ];

But static variables are only cleared the first the function runs. If you want str to start out empty, you have to empty explicitly each time, like so, the most efficient way and prettiest way (As Paul R noted):

char str[BUFSIZE] = "";

which is equivalent to:

char str[BUFSIZE] = { 0 };

and can be done explicitly like this: char str[BUFSIZ]; str[0] = '\0';

or so, maybe to most logical way to someone new to C:

char str[BUFSIZ];
strcpy(str, "");

or so, explicitly clearing all the array, least efficient and unnecessary:

char str[BUFSIZ];
memset(str, 0, sizeof (str));
Amigable Clark Kant
Probably better style to just use `char str[BUFSIZ] = "";`
Paul R
Sorry if I'm being obtuse but isn't the default starting value for a string in C if you do not initialise it to be "\0", like how an int would have a 0? Also I tried using a static declaration as well as assigning a `NULL` value to the first element, but yet the assertion is failing.
jon2512chua
@jon2512chua, no, there is no starting value for auto variables in C. For global values and static values the start values are 0.
Amigable Clark Kant
Ok got it thanks!
jon2512chua
+3  A: 

strcmp returns 0 when strings match, so your tests need to be inverted, e.g.

assert(strcmp(str, "hello") == 0);

Paul R
Hey sorry didn't see your reply earlier, but thanks for your help! :)
jon2512chua
+3  A: 

strcmp returns 0 if both strings are same. assert takes 0 (false) as an indication that the test failed and will report error. So the test should be:

assert(strcmp(str, "") == 0);
Vijay Mathew
Lol didn't notice that, thanks!
jon2512chua