117k views
4 votes
What will be the output of the following C program?

#include
#include
int main() (
char *s;
char *fun();
s = fun();
printf(%sn, s);
return 0;
)
char *fun() (
char buffer[30];
strcpy(buffer, RAM);
return (buffer);
)

a) RAM
b) Compiler error
c) Segmentation fault
d) Null pointer exception

1 Answer

2 votes

Final answer:

The output of the given C program will be undefined because it invokes undefined behavior.

Step-by-step explanation:

The output of the given C program will be undefined because it invokes undefined behavior.

This is because the function fun() is returning the address of a local variable buffer, which is a local array with automatic storage duration. After the function fun() is executed, the buffer array is deallocated, and accessing its address outside the function leads to undefined behavior.

To resolve this issue, you should either allocate memory dynamically using malloc() or pass a pointer as an argument and write the result into that pointer.

User Neil Wilson
by
9.0k points