OA. free
Free
IBM Core Computer Science Core Computer Science Medium

What will be the result when the following code is executed (assume all required header...

IBM technical mcq question with a worked answer. Free to practise - no sign-up.

What will be the result when the following code is executed (assume all required header files included):

void f1(char *s)
{
    strcpy(s, "hi");
}

int main()
{
    int (*myf_var)(char *) = strlen;
    f1((char *)myf_var);
    printf("len=%d\n", myf_var("hello"));
    return 0;
}

Pick ONE option

Choose one option.
Show answer & explanation
Answer: D. Segmentation Fault

The code declares myf_var as a function pointer to strlen. In f1((char *)myf_var), the function pointer address is cast to a char* and passed to f1, which then calls strcpy(s, "hi") to write data directly into memory where the function pointer code resides. This corrupts the function pointer. When myf_var("hello") is called afterward, it attempts to invoke corrupted memory, resulting in a segmentation fault.

Step-by-step Derivation:
Step-by-step execution:

  1. int (*myf_var)(char *) declares a function pointer initialized to strlen (the address of the strlen function in code memory).
  2. f1((char *)myf_var) casts the function pointer's address to char* and passes it to f1.
  3. Inside f1, strcpy(s, "hi") writes the string "hi\0" (3 bytes) to the memory location where the function pointer pointed—directly into the code/data segment.
  4. This overwrites the function code or corrupts the pointer value stored in myf_var.
  5. When myf_var("hello") attempts to call the function, the corrupted pointer/code causes a segmentation fault at runtime (dereferencing invalid memory).