-8

I have written a code to print the name of 2 workers, but instead it prints garbage.

cout << "highest salary: " << highestSalary.getID() << " " << highestSalary.getName() << endl;

cout << "hardest worker: " << mostHours.getID() << " " << mostHours.getName();

the function getName() is defined in the worker class as:

char* Worker::getName()
{
    char temp[20];

    int i;
    strcpy(temp, name);

    return temp;
}

going through this on the debugger I tried putting the value of highestSalary.getName() inside a ver char* temp, and the value was what i anticipated, let's say "bob", but after the cout the value was "" and the cout printed garbage.

  • This behavior is SO undefined ;) – Andy Prowl Mar 10 '13 at 13:11
  • 1
    Hint: `std::string` is tremendously helpful for, lets say, everything that has to do with characters. – Zeta Mar 10 '13 at 13:12
  • 7
    Why can't you friggin' google it? Seriously... This is asked like twice a day... Couldn't you just find one of the previous questions? Why? *Why?* ***Why?*** –  Mar 10 '13 at 13:12
  • 4
    Buffer overflow fail. Lack of `std::string` fail. Getter fail. Everything fail. –  Mar 10 '13 at 13:17
  • 1
    Here's the main dupe: http://stackoverflow.com/questions/6441218/can-a-local-variables-memory-be-accessed-outside-its-scope – chris Mar 10 '13 at 14:11

2 Answers2

8

NO NO NO, you are returning a pointer to a local function variable. That's why it crashes.

Do this instead:

std::string Worker::getName()
{
   std::string temp(name); // not sure what type of name is...
   return temp;
}

Don't forget to #include<string>.

Now you have real C++, not C and pointers.

Tony The Lion
  • 61,704
  • 67
  • 242
  • 415
1

You are passing a pointer to a local variable. Once your function ends, this variable is gone.

If this is C++ you should use the string class. If for whatever reason you don't, at least be const correct:

const char* Worker::getName() const 
{
    return name;
}
nvoigt
  • 75,013
  • 26
  • 93
  • 142
  • The const after the function name means that this function will not alter the state of the class instance it's called on. – nvoigt Mar 10 '13 at 18:15