alanlittle alanlittle - 2 months ago 14
C++ Question

C++ Function "Automatic" Return Value?

How is this working? In writing this function, I forgot to include a

return
statement:

char *getV(const char *var) {
char *val = nullptr;
forward_list<formField>::iterator idx;

formField ffld;
idx = _fields.begin();
while (idx != _fields.end()) {
ffld = *idx;
if (strcmp(ffld.Name, var) == 0) {
val = ffld.Val;
break;
}
idx++;
}
}


Here is
formField
:

struct formField {
char *Name = nullptr;
char *Val = nullptr;
};


Here's how I'm calling the function:

int main () {
form fdata;

fdata.add("FirstName", "Alan");

char *fval = fdata.getV("FirstName");
if (fval != nullptr) cout << fval;
else cout << "not found";
cout << "\n";
}


I didn't notice the missing
return
until later, after testing the function and writing other code which uses it. The function is supposed to return
*val
...and it does! How?

Answer

The calling convention of your platform specifies how the function returns the value it wants to be returned to the caller (e.g: saved in a register). Since the register exists, the caller code just takes the value it finds there, possibly garbage, or the actual good value by chance. Either way, your program invokes undefined behaviour, it cannot be trusted any more.

The solution is to turn the compiler warnings on. E.g, on GCC or Clang:

g++ -Wall -Wextra -Werror