-2

This is my C++ code .
According to me , it should give output:
abc
Garbage
abc

But it is giving output:
abc
Garbage
Garbage

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


char **func()
{
char* PA = new char[10];
PA[0]='a';
PA[1]='b';
PA[2]='c';
PA[3]='\0';

printf("%s\n",PA);
printf("Garbage\n");

char **PPA = &PA;
return PPA;

}

int main()
{
 printf("%s\n",*func());
 return 0;
}

Where am I doing wrong?

Badman
  • 407
  • 5
  • 17

1 Answers1

3
char **PPA = &PA;

Retrieves the address of the variable PA itsself, which is an automatic variable and goes out of scope as soon as the function terminates. That means you have undefined behavior here. The C standard doesn't guarantee any consistent behavior, so anything may happen, including what you experienced.

To fix that, you could change the function prototype to char* func() and return PA directly and remove PPA altogether.

cadaniluk
  • 15,027
  • 2
  • 39
  • 67