What will be the result when the following code is executed (assume all required header...
IBM technical mcq question, verified 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
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:
int (*myf_var)(char *)declares a function pointer initialized tostrlen(the address of the strlen function in code memory).f1((char *)myf_var)casts the function pointer's address tochar*and passes it to f1.- 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. - This overwrites the function code or corrupts the pointer value stored in myf_var.
- When
myf_var("hello")attempts to call the function, the corrupted pointer/code causes a segmentation fault at runtime (dereferencing invalid memory).