How to use assert to check string

I'm currently trying to test the strcat() function that I wrote myself. Instead of printing the outputs and checking them line by line manually, I decided to use assert from assert.h. The problem is that assert shows errors, even if the results look completely normal. Below is my code:

 void mystrcat_test() { char str[BUFSIZ]; assert(strcmp(str, "")); mystrcat(str, "hello"); assert(strcmo(str, "hello")); } 
+4
source share
3 answers

strcmp returns 0 if both lines are the same. assert accepts 0 (false) as an indication of the loss of the test and an error message. So the test should be:

 assert(strcmp(str, "") == 0); 
+5
source

strcmp returns 0 when strings match, so your tests should be inverted, for example.

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

+4
source

In C, if (automatically) the variables are not set explicitly, they can contain any value, not just zero, even if it is shared. For example, int int is often 0 if not specified, but can actually be any value. The same goes for all types, including char arrays.

str in this case can contain anything, i.e. cannot be empty. It is not initialized, so your statement for strcmp with "" may amaze you.

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

Instead, it can be written as:

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

or

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

If you want it to be empty, you can use a static declaration, for example:

 static char str[BUFSIZ]; 

But static variables are only cleared, the first runs the function. If you want str to start empty, you must explicitly clean each time, thus the most efficient way and the most beautiful way (as Pavel R. noted):

 char str[BUFSIZE] = ""; 

which is equivalent to:

 char str[BUFSIZE] = { 0 }; 

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

or so, perhaps the most logical way for someone new to C:

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

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

 char str[BUFSIZ]; memset(str, 0, sizeof (str)); 
+2
source

All Articles