0

Let's say we have following code:

int func(char str[], int len) {
    // Don't return anything here.
}

int main() {
    char str[] = "Hello";
    int result = func(str, strlen(str));
    printf("%d\n", result);
}

It will print some string value -1679929632 on my computer. And it changes from time to time when I execute.

Can anyone explain why this happen?

Praxeolitic
  • 22,455
  • 16
  • 75
  • 126
Bill Randerson
  • 1,028
  • 1
  • 11
  • 29
  • 2
    It's undefined behavior. It could be anything or crash. – Retired Ninja Jan 21 '15 at 05:10
  • Is this value read from StackFrame? What's the potential value is this from? Some local variable or return address? – Bill Randerson Jan 21 '15 at 05:11
  • This may help you understand: http://stackoverflow.com/questions/12376461/what-actually-happens-when-a-function-with-the-warning-control-reaches-end-o The value is generally whatever happens to be in the register that is used to return a value of that type. – Retired Ninja Jan 21 '15 at 05:14
  • So basically the caller simply tries to read some register as return value, and caller doesn't have any knowledge as if the callee really returns something or not. Right? – Bill Randerson Jan 21 '15 at 08:39

1 Answers1

5

If no return statement appears in a function definition, control automatically returns to the calling function after the last statement of the called function is executed. In this case, the return value of the called function is undefined. If a return value is not required, declare the function to have void return type; otherwise, the default return type is int.

As mentioned above its undefined so finding root cause behind some random value as return will be useless.

Dayal rai
  • 6,548
  • 22
  • 29