简体   繁体   中英

Trouble understanding the use of void (*fptr)(void) pointer in an array of void

I have trouble understanding the code of a C program that is supposed to be vulnerable.

We have this definition typedef void (*fptr)(void); , and I leave the partial code above. I don't quite have a problem understanding the instruction fptr p = pat_on_back; , which just defines an fptr pointer that points to a function that never gets executed because that instruction just defines and initializes a pointer (right?).

My problem is understanding instruction fptr ptrs[3] = { NULL, get_wisdom, put_wisdom }; . How come this instruction works when the type fptr is clearly being used to declare and initialize an array of the void? Shouldn't just receive a single void parameter?

For the matter, the get_wisdom() and put_wisdom() functions both receive and return void. This little program is to fill and print a simple linked list of chars called 'wisdom'. The functions get_wisdom() and put_wisdom() does exactly what it apparently seems to do.

char greeting[] = "Hello there\n1. Receive wisdom\n2. Add wisdom\nSelection >";
char prompt[] = "Enter some wisdom\n";
char pat[] = "Achievement unlocked!\n";
char secret[] = "secret key";

typedef void (*fptr)(void);

void pat_on_back(void) {
  write(outfd, pat, sizeof(pat));
  return;
}

void put_wisdom(void) {
  . . .
}

void get_wisdom(void) {
  . . .
} 

fptr  ptrs[3] = { NULL, get_wisdom, put_wisdom };

int main(int argc, char *argv[]) {

  while(1) {
      char  buf[1024] = {0};
      int r;
      fptr p = pat_on_back;
      r = write(outfd, greeting, sizeof(greeting)-sizeof(char));
      if(r < 0) {
        break;
      }
      r = read(infd, buf, sizeof(buf)-sizeof(char));
      if(r > 0) {
        buf[r] = '\0';
        int s = atoi(buf);
        fptr tmp = ptrs[s];
        tmp();
      } else {
        break;
      }
  }

  return 0;
}
typedef void (*fptr)(void);

Defines the fptr type as a pointer to a function that returns a value of the indicated type (void) and requires the indicated parameters (void)

fptr  ptrs[3] = { NULL, get_wisdom, put_wisdom };

Defines ptrs as a vector of 3 elements, each is a pointer to one function that has void as parameter (anything), and returns void.

  • ptrs[0] = NULL ; The first pointer point to NULL.
  • ptrs[1] = get_wisdom ; The second pointer point to the function "get_wisdom".
  • ptrs[2] = put_wisdom ; The third pointer point to the function "put_wisdom".

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