2

I got a problem with one of my final function. My goal is too treat a picture. I declare in a header :

#define PICTURESIZE 1024
typedef unsigned char Picture[PICTURESIZE][PICTURESIZE];
typedef unsigned char LinearBlocPicture[PICTURESIZE*PICTURESIZE];

I include this header in an other file, where i got only one function :

LinearBlocPicture picture2BlocVector (Picture image){
    LinearBlocPicture pictureModify;
    int curseurLinearBlocPicture = 0; 
    unsigned char blocPixel[8][8]; 
    unsigned char* bufferLinearBlocPicture;
    int x,y,i,j,k;  


    for(y=0; y < 1024; y=y+8) { 
        for(x=0; x < 1024; x=x+8) { 
            for(j=0; j < 8; j++) { 
                for(i=0; i<8; i++) { 
                    blocPixel[i][j] = image[x+i][y+j];
                } 
            }  

            bufferLinearBlocPicture = bloc2Vector (blocPixel);

            for (k=0; k<64; k++){
                pictureModify[curseurLinearBlocPicture+k] = bufferLinearBlocPicture[k];
            }

            curseurLinearBlocPicture = curseurLinearBlocPicture + 64;
        } 
    }

    return pictureModify;
}

This function apply my treatment, the problem come from the return value, and what is expected to be return. I got this when i try to compilate :

First line error: ‘picture2BlocVector’ declared as function returning an array
Application.c: In function ‘picture2BlocVector’:
Last line: warning: return makes integer from pointer without a cast
Last line: warning: function returns address of local variable

I don't understand why there is a problem for the return type, because i declare properly my type LinearBlocPicture. The pointer problem come from this line i think :

pictureModify[curseurLinearBlocPicture+k] = bufferLinearBlocPicture[k];

I'm not sure to be allowed to do this. Thanks for your help.

yan
  • 20,644
  • 3
  • 38
  • 48
Evans Belloeil
  • 2,413
  • 7
  • 43
  • 76

1 Answers1

2

In C, arrays are often "decayed" to pointer values, so when you return an array, you're essentially returning the address of its first element. In your sample code, you allocate pictureModify on a local stack, and attempt to return its address. When your function returns, all variables declared during its execution will be cleaned up -- this includes your local buffer.

To get around this you have a few options:

  1. Use malloc() to allocate a block of memory, write your results to it and then return a pointer to it. When you do this, you need to make sure your calling code will call free() on it.
  2. Allocate memory in your calling code, and pass a pointer to that buffer to picture2BlocVector. This way, you're localizing all memory management to one place. In this scenario, you can even create a local variable and pass its address.
yan
  • 20,644
  • 3
  • 38
  • 48