-1

So i'm trying to optimize the managment of my memory in my code.

Here's a sample of the code :

    Image image;

    int main(int argc, char *argv[])
    {

    image = (Image) malloc(sizeof (struct image));

    image = doSomething(image);


    }

    Image doSomething(Image imageInput) {
    Image imageResult;

    imageResult = (Image) malloc(sizeof (struct image));

    //Code does something here 

    return imageResult;

    }

When is it proper to use the free(); in my example ?

Image image;

int main(int argc, char *argv[])
{

image = (Image) malloc(sizeof (struct image));

image = doSomething(image);


 free(image);
}

Image doSomething(Image imageInput) {
Image imageResult;

imageResult = (Image) malloc(sizeof (struct image));

//Code does something here 

free(imageInput);
return imageResult;

}

The only time i can see is the "imageInput" variable that is supossed to be copied in the function and is suppose to be erased after the function ends.

Is it overkill to free a function variable ?

And at the end of the execution of the application too.

Cyberflow
  • 1,255
  • 5
  • 14
  • 24
  • You *can't* `free` a function variable: you can only `free` memory that was allocated with the `malloc` family of functions. The function variables' life ends when you exit the function anyway. – Weather Vane Nov 24 '16 at 19:03
  • 1
    [Please see this discussion on why not to cast the return value of `malloc()` and family in `C`.](http://stackoverflow.com/q/605845/2173917). – Sourav Ghosh Nov 24 '16 at 19:06
  • 1
    By (presumably) defining a pointer to your image as a type, you made it unclear exactly what you are allocating, and how much. `image = (Image) malloc(sizeof (struct image));` seems leery, since you have used `image` *and* `struct image` and it is unclear if you allocate only enough memory for a `pointer`. It is poor practice to define pointer types. – Weather Vane Nov 24 '16 at 19:09
  • 2
    [typedef pointers is not a good idea](http://discuss.fogcreek.com/joelonsoftware1/default.asp?cmd=show&ixPost=10506), especially if you don't show it. – David Ranieri Nov 24 '16 at 19:13
  • After `image = doSomething(image);` since the function returns another pointer from `malloc`, you will not be able to free the original allocation - memory leak. – Weather Vane Nov 24 '16 at 19:14

1 Answers1

0

Finally i've used valgrind to analyze any memory leaks.

Pretty helpfull to guide someone into this task. Helped me to learn when to do a free() and where.

Here's a usefull link : Valgrind website

Cyberflow
  • 1,255
  • 5
  • 14
  • 24