0
char* func()
{
  const int size = 24;
  char bin[size];
  char *temp;
  for(int i=0; i<23; i++)
    bin[i] = '1';
  bin[23] = '\0';
  temp = bin;
  return temp;
}

int main()
{
  char *s;
  s = func();
  cout << s << endl; //prints out weird values

  return 0;
}

When compiled and ran, it print random values. In the function func, I initialized a char array and tried to return it. Upon returning it and printing it in main, it prints out weird values. What is wrong? Any help would be appreciated.

user3239138
  • 143
  • 4
  • 17

2 Answers2

1
char bin[size];

allocate memory on the stack, you cannot refer to that location after the function returns: "char *s" is assigned a value that refer to an invalid memory location.

0

You must not use pointers to freed space, like the stack of a function which has finished executing.
This Undefined Behavior means anything goes, even the proverbial demons flying out of your nose.

Your choices:

  • Use a caller-allocated buffer.
  • Use a static buffer (beware reentrancy problems and multithreading woes).
  • Use dynamic allocation (new, new[], malloc() and friends).
  • return a struct (standard container or otherwise) containing the data. Might use dynamic allocation. (Last point courtesy of Matt McNabb).
Deduplicator
  • 44,692
  • 7
  • 66
  • 118