4

In our lecture we had the following example:

int *foo(int x) {
    return &x;
}

int* pt = foo(x);
*pt = 17;

It was shown as a bad example, but not further explained. Why is this bad?

undur_gongor
  • 15,657
  • 5
  • 63
  • 75
f1sh3r0
  • 55
  • 4

3 Answers3

5

Bad thing is that you are returning a pointer to an automatic local variable. It will no longer be exist once function returns and then the statement *pt = 17; will cause program to behave erratically.

A pointer to static local variable can be returned.

int *foo() {
    static int x;
    return &x;
}
int* pt = foo();
*pt = 17; 
haccks
  • 104,019
  • 25
  • 176
  • 264
4

In foo the variable x is local hence it ceases to exist after the method exits. When a function returns, its automatic, local variables are discarded, so the returned pointer in this case is invalid (it points to an array that no longer exists).

int* pt = foo(x);
*pt = 17; 

Hence, now access to pt results in Undefined Behavior. You should malloc it instead:

int *foo() 
{
    int *x = malloc(sizeof(int));
    *x = 0;
    return x;
}

int* pt = foo();
*pt = 17;
free(pt);
Sadique
  • 22,572
  • 7
  • 65
  • 91
4

Here

int *foo(int x) {

x is a local, non-static variable. By doing

return &x;

you return the address of the local variable x. It exists as long as the function does , and when the function exits, this address will be invalid for you to play with. By using

*pt = 17;

you dereference this address and write 17 to this invalid memory location. This triggers Undefined Behavior. This is why the given code is bad.

Spikatrix
  • 20,225
  • 7
  • 37
  • 83