-1
#include <bits/stdc++.h>
using namespace std;

char *fun()
{
    static char arr[1024];
    return arr;
}

int main()
{
    char *str = "geeksforgeeks";
    strcpy(fun(), str);
    str = fun();
    strcpy(str, "geeksquiz");
    cout << fun();
    return 0;
}

The output is geeksquiz. Could someone help me in understanding how the code works step by step? Thank you.

ana
  • 1
  • 1
    This code is invoking Undefined Behaviour, so the answer is: "It works by sheer chance" – Yksisarvinen May 07 '20 at 14:47
  • What is it that you don't understand? `fun` always returns the same pointer to the first element of the same array. – molbdnilo May 07 '20 at 14:51
  • @Yksisarvinen -- I don't see anything that's undefined here. Note that `arr` is `static`, so persists outside the function call. – Pete Becker May 07 '20 at 15:06
  • @Pete What about `char *str = "geeksforgeeks";`? Pretty sure it's UB in C++? – Yksisarvinen May 07 '20 at 15:08
  • 1
    Please read [Why should I not #include ?](https://stackoverflow.com/q/31816095/5910058) – Jesper Juhl May 07 '20 at 15:14
  • 1
    @Yksisarvinen — yes the type of the pointer should be `const char*`. That’s a hard error, not undefined behavior. It’s also enforced laxly, and it’s harmless as long as you don’t try to modify a literal string, so this code is okay in that regard. – Pete Becker May 07 '20 at 22:19
  • @molbdnilo why do we write "char *fun()" but not just "char fun()" for the fun function defination? is it because it returns a string literal? – ana May 09 '20 at 12:58

1 Answers1

0
static char arr[1024]; // << word static here means that every time fun() returns pointer to the same memory.

str = fun(); // now str points to that memory. 
strcpy(str, "geeksquiz"); // copies string into that memory
Michail Highkhan
  • 517
  • 6
  • 18