This is a pretty beginner question but I'm quite sure I'm right and I am quite clearly wrong, so I feel the need to ask: what happens when you dynamically allocate memory on the stack? It stays there after the variable has left the function's scope, right?
Here's the code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
|
Image* imgCreate(int w, int h, int dcs)
{
Image* image = (Image*) malloc (sizeof(Image)); //RELEVANT
assert(image);
image->width = w;
image->height = h;
image->dcs = dcs;
image->buf = malloc (w * h * dcs * sizeof(float));
assert(image->buf);
return image;
}
Image* imgCopy(Image* image)
{
int w = imgGetWidth(image);
int h = imgGetHeight(image);
int dcs = imgGetDimColorSpace(image);
Image* img1=imgCreate(w,h,dcs); //RELEVANT
int x,y;
float rgb[3];
for (y=0;y<h;y++){
for (x=0;x<w;x++) {
imgGetPixel3fv(image,x,y,rgb);
imgSetPixel3fv(img1,x,y,rgb);
}
}
return img1;
}
void imgMedian(Image* img)
{
int x,y,dcs=img->dcs,z=img->width*dcs;
Image* copy = imgCreate(img->width,img->height,img->dcs); //RELEVANT
float* img_buf = img->buf;
copy->dcs=dcs;
copy->height=img->height;
copy->width=img->width;
for(x=0;x<img->dcs*img->width;x++)
copy->buf[x]=img_buf[x];
for(y=1;y<img->height-1;y++)
{
copy->buf[y*z]=img_buf[y*z];
for(x=1;x<img->dcs*(img->width-1);x++)
{
copy->buf[x+y*z]=(img_buf[x-dcs+(y+1)*z]+img_buf[x+dcs+(y+1)*z]+img_buf[x-dcs+(y-1)*z]+img_buf[x+dcs+(y-1)*z]+
img_buf[x-dcs+y*z]+img_buf[x+dcs+y*z]+img_buf[x+(y-1)*z]+img_buf[x+(y+1)*z]+img_buf[x+y*z])/9;
}
copy->buf[y*z+x]=img_buf[y*z+x];
copy->buf[y*z+x]=img_buf[y*z+x+1];
copy->buf[y*z+x]=img_buf[y*z+x+2];
}
for(x=0;x<img->dcs*img->width;x++)
copy->buf[x+y*z]=img->buf[x+y*z];
imgDestroy(img);
img=copy; //RELEVANT
//img=imgCopy(copy); //RELEVANT
}
|
Those are just the relevant functions, of course. Really, all that matters is that
copy
(in
imgMedian()
) is created through
imgCreate()
, which dynamically allocates it's memory slot, and
img
then loses it's own object and instead points to
copy
's memory slot.
However, should I then manipulate
img
after calling
imgMedian()
, all the information within it has been lost.
However, should I, instead of doing
img=copy
use
img=imgCopy(copy);
, everything works fine.
I feel like I'm making a really stupid mistake here.