开发者

Is output parameters considers to violate the principle of returning local references?

I've this code:

#include <stdio.h>
#include <stdlib.h>
#define OUT

void getDataFromServer(OUT int** array, OUT int* size)
{
    int tmpArr[] = {0x00, 0x01, 0x02, 0x03,  0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F,
                        0x10, 0x11, 0x12, 0x13,  0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F};
    *size = sizeof tmpArr / sizeof(int);
    *array = tmpArr;
}

int main(void)
{
    int size = 0;
    int* dataFromServer;
    getDataFromServer(&dataFromServer, &size);

    int x;
    for (x开发者_如何学JAVA=0; x < size; x++)
        printf("%d ", dataFromServer[x]);
    printf("\n\n");

    return 0;
}

The for loop inside the main prints garbage data.. Is this because of the OUT int** array parameter access data local to a function?

Thanks.


Yes, no matter how you do it, you can't send the address of a local variable out of a function and expect it to continue to be valid once the function returns. The same argument holds for function return values or for "out parameters", or, in general, setting any memory location to point to the local variable.

It's often said that the variables are removed from the stack, or become "garbage"; it helps to realize that what actually happens is that the space is reused for the local variables of other functions, for parameters used to call other functions, etc. This is why sometimes the "garbage" variables appear to be still valid -- because their space hasn't been reused yet.


Yes, exactly. Since tmpArr is local to getDataFromServer, it ceases to exist when the function returns. Pointers into it are now pointers to garbage.

You should think about who is responsible for allocating memory to hold the data from the server and who is responsible for freeing it. In this case, the function is responsible for freeing it, which obviously can't work. Either side can allocate, but the caller must free!


When getDataFromServer exits, all local variables are popped off of the stack. The pointer you're using is now pointing at an area of memory that has more or less been wiped out. Either use malloc and copy the data into newly allocated memory (on the heap), or make tmpArr into a static variable.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜