Note that there are some explanatory texts on larger screens.

plurals
  1. POinteresting strcmp implementation failure. (C)
    primarykey
    data
    text
    <p>I am working on a small project which I have no access to any C standard library.( building a microkernel in ARM structure from the scratch. Even printf had to be implemented )</p> <p>Under this circumstance I implemented strcmp, using Duff's machine methodology.</p> <p>the following is the entire code.</p> <pre><code>int strcmp ( const char *str1, const char *str2 ) { while ( *str1 || *str2 ) if ( *(str1++) != *(str2++) ) return *str1 - *str2; return 0; } </code></pre> <p>It made sense; and for some while it seemed to work on test cases, until an end-system fail happened. I traced down and it came to this strcmp.</p> <p>At first I thought it incremented str1 first then compared against str2 BEFORE str2 incremented. <strong>1. It turned out not to be but could anyone please verify that it can happen in some cases?</strong></p> <p>I then figured that the problem was in *str1 - *str2 so changed it to return 1. i.e., the resulting code is as follows:</p> <pre><code> while ( *str1 || *str2 ) if ( *(str1++) != *(str2++) ) return 1; return 0; </code></pre> <p>while all I wanted was an 'equals' check, so changing into '1' bore no problem, but I still wonder why the original code failed. <strong>2. Could someone give a light or a suggestion as to how it could have failed?</strong> I would rather want the strcmp to follow the standard C interface that it returns a non-zero value that tells more about the str1 and str2.</p> <p>the test cases were:</p> <pre><code>code_t // a function pointer type program_find ( char *program ) { if (strcmp( program, "exit" ) == 0) return .... else if (strcmp( program, "k1" ) == 0) return .... else if (strcmp( program, "k3" ) == 0) return .... else if (strcmp( program, "perf" ) == 0) return .... else if (strcmp( program, "test_libc" ) == 0) return .... } </code></pre> <p>when *program was "k3" it returned "k1", and "test_libc" returned "perf".</p> <p>The original problem was solved by giving it "return 1", so this question is purely for C interests. A suggestion or linkage to strcmp documentation is also welcome. I have seen the spec interface for IEEE </p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload