简体   繁体   中英

Is this a wrong approach for sentinel linear search?

I was reading Algorithms Unlocked by Thomas H. Cormen and I ran into an algorithm for sentinel linear search but I wrote it in a slightly different manner. Though this code also works, I wanted to know if approach is wrong because I am accessing memory that is not mine?

CODE:

int lsearch (int a[5], int n) {

    int i = 0;

    a[5] = n;

    while (a[i] != n)
        i ++;

    if (i == 5)
        return -1;

    return i;
}

You're setting the value of a memory location you don't own. You're overwriting memory that lies right after the allocated memory of your array (that's an out of bounds access). Your program might run, but it is conceptually wrong (and depending on the compiler and the security checks in place, might not work in other situations)

If the argument passed in for the a parameter has less than 6 elements, then accessing a[5] is undefined behavior and will cause problems in many cases. Given the declaration of a , I'm assuming that you are calling the function with a 5-element array, so the code is wrong.

If the argument has 6 or more elements, the code will work. But in that case:

  1. The parameter declaration as int a[5] is misleading.
  2. Having a search function which modifies the input array can be unexpected by the caller.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM