warning: function returns address of local variable [-Wreturn-local-addr]

前端 未结 4 664
Happy的楠姐
Happy的楠姐 2020-12-22 10:58

I get this error when compiling and have checked out other questions here with no further progress:

funciones.c: In function ‘Lyapunov’: ../funciones.

相关标签:
4条回答
  • 2020-12-22 11:34

    to avoid all the messy malloc/free calls, etc. define the rgb in the caller and pass the address to the function.

    0 讨论(0)
  • 2020-12-22 11:37

    You trying to return an array rgb which stops existing outside of its local scope ( also the scope of the function ), which stops existing when you return from the function. Arrays cannot be returned by value.

    You can put the array in a struct:

    struct rgb_hold
    {
        char rgb[3] ;
    } ;
    

    and return the struct, which can be returned by value.

    0 讨论(0)
  • 2020-12-22 11:41
    unsigned char rgb[3];
    

    is local to function and the scope of this array is within the function Lyapunov so once you exit the function this memory is no more valid. So the warning you are getting is the right one which says never return the local variables address which will lead to undefined behavior when used outside its scope.

    Have your memory allocated of heap and then return the pointer as shown below.

    unsigned char *rgb = malloc(3);
    
    0 讨论(0)
  • 2020-12-22 11:43

    You can use malloc as suggested, but looking at your code better idea would be to have a single static buffer passed to a function to have it's result (since you are using the buffer just once, and then discarding it's data), such that the function signature will be:

    void Lyapunov(int ai, int bi, unsigned char rgb[]);
    

    Then prior the use of the function you will need to define the buffer:

    unsigned char rgb[3];
    

    and then use it in your loop

    Lyapunov(col,linea, rgb);
    

    This way you will not need to worry about any memory leaks (resulting from the function).

    0 讨论(0)
提交回复
热议问题