Search code examples
carraysfor-loopstrcmpstrcpy

What is wrong with the following strcmp() code?


I have a multidimensional array of a structure, whose content is initialized to '\0' initially and later occasionally. After some values are inserted, it is sorted on fing_print in an ascending order. Then the first n entries of the sorted array is copied into another array. In my implementation some of the array elements might not be assigned values, so they contain the '\0' values assigned to them earlier and they need to be ignored when copying into the other array.

My problem is, the code breaks at "__DEFINE_CPP_OVERLOAD_SECURE_FUNC_0_1( errno_t, strcpy_s, _Post_z_ char, _Destination, _In_z_ char const*, _Source ).

And upon debugging I have noticed that it breaks at the strcpy_s(selected[j][r].fing_print, hash_table[j][i].fing_print); line when only one of the j (BUCKETS) contains data.

for (int j = 0; j < BUCKETS; ++j) {
    // select rep fps here according to select size

    for (int i = 0,r=0; i<B_ENTRIES, r < SELECT_SIZE; ++i) {
        if (!strcmp(hash_table[j][i].fing_print, garb)) {
            // garb contains '\0'
            continue;
        }
        prev = i-1;
        if (!strcmp(hash_table[j]i].fing_print,
                    hash_table[j][prev].fing_print)) {
            // make sure the same fingerprint is not selected twice
            continue;
        }
        strcpy_s(selected[j][r].fing_print,
                 hash_table[j][i].fing_print);
        ++r;    
    }
}

Solution

  • As stated in the comment section my mistake was in using the comma in the loop exit conditions for (int i = 0,r=0; i<B_ENTRIES, r < SELECT_SIZE; ++i) .correcting it to the following worked fine.

    for (int j = 0; j < BUCKETS; ++j) {
        // select rep fps here according to select size
    for (int i = 0,r=0; i<B_ENTRIES && r < SELECT_SIZE; ++i) {
        if (!strcmp(hash_table[j][i].fing_print, garb)) {
            // garb contains '\0'
            continue;
        }
        prev = i-1;
        if (!strcmp(hash_table[j]i].fing_print,
                    hash_table[j][prev].fing_print)) {
            // make sure the same fingerprint is not selected twice
            continue;
        }
        strcpy_s(selected[j][r].fing_print,
                 hash_table[j][i].fing_print);
        ++r;    
      }
    }
    

    The strcpy_s() function worked fine as it is, but again as pointed out in the comments above it missed one parameter which is the size of the destination array and so should be corrected to

    strcpy_s(selected[j][r].fing_print,sizeof(selected[j][r].fing_print),
                 hash_table[j][i].fing_print);