0

This method returns a pointer to the first element of an int array

int *getNumbers(){
    int *retPtr;
    int ret[6];
    ret[0] = 1;
    ret[1] = 2;
    ret[2] = 3;
    ret[3] = 4;
    ret[4] = 5;
    ret[5] = 6;

    retPtr = ret;
    return retPtr;
}

At this point I can do *(arryPtr + x) and get the array values out fine

int* arryPtr = getNumbers();
int result = NumberProcess1(arryPtr); 

Once I get into this method however I can't do that.

int NumberProcess1(int* numbers)

I keep getting eronious values and I'm not sure why.

DotNetRussell
  • 9,716
  • 10
  • 56
  • 111

2 Answers2

4

ret[6]; is allocated on stack & return retPtr returns the address to where that variable is placed in the stack.
The thing with stack is that frames on it get pushed & pop'ed so the location your pointer points to may be over-wriiten by the next stack frame.

Hence you should never return a pointer to a local variable.

Allocate on heap instead:

int *ret = malloc(sizeof(int));
brokenfoot
  • 11,083
  • 10
  • 59
  • 80
1

int ret[6]; declares an array that only exists within the getNumbers() function. Once that function returns, the memory is no longer valid. Trying to use it causes undefined behaviour.

One solution to this would be to make it static int ret[6];

Other solutions include having the caller allocate the buffer, and using dynamic allocation.

Also, the function should be int *getNumbers(void) - the void is important as it forms a prototype.

M.M
  • 138,810
  • 21
  • 208
  • 365