0

I have learned that whenever a function ends, every local variable declared inside of it is erased. That's why we must use malloc when declaring an array.

But when I think about that again when a function ends what is really erased (in case I defined an array) is the pointer to that array and not the array itself, So we could simply solve the former problem by returning the pointer.

Here is a look at my code, why did it work while my professor said "we must use malloc"?

#include <stdio.h>

int * test ()
{
    int arr[3]={4,5,6};
    return arr;
}
int main() {
    printf("Hello, World!\n");
    int *arr=test();
    printf("%d",arr[1]);
    return 0;
}

Edit: I'm working according to the C99 standard if that does make a difference.

  • 3
    `malloc` gives long-lasting storage. Your local `arr` only exists while `test` runs. – stark Apr 06 '20 at 12:10
  • Your code invokes *undefined behavior*. It's that simple. The lifetime of `int arr[3]` in `test` ceases once `test` exits, and any reference to said-memory thereafter is UB. In `main`, `printf("%d",arr[1]);` derefernces a pointer that has no "there" there. Whether it "works", "appears to work", etc. is irrelevant. It's wrong. [Read this Q&A](https://stackoverflow.com/questions/6441218/can-a-local-variables-memory-be-accessed-outside-its-scope/6445794). – WhozCraig Apr 06 '20 at 12:13
  • It's unclear what you mean by "erased". The memory isn't guaranteed to be *cleared*/*overwritten*. It will be *freed*, and thus no longer valid to access. – ikegami Apr 06 '20 at 12:14
  • Your stack has not overwritten the memory where arr is stored in the example. Call another function after assigning the arr or assign a few variables and you will overwrite that memory. – fuentesj Apr 06 '20 at 12:15
  • You return the pointer, the value of where in memory the data is, but the data may not be there because the stack frame associated to the function does not exist anymore. Thus, it will lead to undefined behaviour. – CRM Apr 06 '20 at 12:15

1 Answers1

0

Option 1:
Change it to static

 static int arr[3]={4,5,6};

Lifetime of a static variable is throughout the program. So we can always create a local static array and return it.

Option 2:
Create a struct

  struct wrapper { 
     int arr[3]; 
  }; 

The reason this is, array members of structures are deeply copied.

Dickens A S
  • 3,824
  • 2
  • 22
  • 45