0
#include <iostream>
#include <string.h>
using namespace std;
/*
 The functions defined below are attempting to return address of a local 
 variable and if my understand is correct...the main function should be
 getting garbage.
*/
int *test1(){
   int a[2]={1,2};
   return a; //returning address of a local variable - should not work.
}
char *test2(){
   char a[2]={'a','b'};
   return a; //returning address of a local variable - should not work.
}
char *test3(){
   char a[1];
   strcpy(a,"b");
   return a; //returning address of a local variable - should not work.
}
char *test4(){
   char a[2];
   strcpy(a,"c");
   return a; //returning address of a local variable - should not work.
}
int main()
{
  int *b= test1();
  cout<<*b<<endl; //gives back garbage.

  char *c=test2();
  cout<<*c<<endl; //gives back garbage.

  char *d=test3();
  cout<<*d<<endl; //this works - why?

  char *e=test4();
  cout<<*e<<endl; //gives back garbage.

  return 0;
}

As far as my understanding goes regarding function calls and memory management this example program baffles me. If I understand things right, the reason why b=test1() and c=test2() don't work is because they are trying to return address of local variables that are wiped off once the stack memory pops the functions out. But then why is d=test3() working?

2 Answers2

3

You got unlucky because the program failed to blow up.

strcpy(a, "b"); in test3 is fundamentally evil, as there is room for 1 character in a, and strcpy is known to copy the one character in the double quote, plus a termination NUL character, which overwrites memory that your program doesn't really have allocated.

One would advise you to turn your compiler warning levels on the highest level they go. Most compilers will politely give you at least a warning message about it.

EvilTeach
  • 28,120
  • 21
  • 85
  • 141
0

The reason why you're third example worked can be summed up as "the phase of the moon was right".

All examples are undefined behaviour, because they return references (or pointers) to local variables. Undefined behaviour means that really anything can happen -- including sometimes the right thingTM, i.e. what you actually meant to happen.

ex-bart
  • 1,352
  • 8
  • 9