I know this won\'T work because the variable x gets destroyed when the function returns:
int* myFunction()
{
int x = 4; return &x;
}
<
Your second code snippet is correct.
To help avoid memory leaks, I let the coding conventions help me.
xxxCreate() will allocate memory for xxx and initialize it. xxxDelete() will destroy/corrupt xxx and free it.
xxxInit() will initialize xxx (never allocate) xxxDestroy() will destroy/corrupt xxx (never free)
Additionally, I try to add the code to delete/destroy/free as soon as I add the code to create/init/malloc. It's not perfect, but I find that it helps me differentiate between items that need to be freed and those that don't, as well as reducing the likelihood that I will forget to free something at a later time.